/**
         * <summary>Attempts to add the MechanicQuery specified by toAdd to the file MechanicQueryFilePath</summary>
         * <param name="toAdd">Mechanic Query to add</param>
         */
        public override bool AddData(MechanicQuery toAdd)
        {
            DataContractJsonSerializer querySerializer = new DataContractJsonSerializer(
                typeof(List <MechanicQuery>)
                );
            List <MechanicQuery> retList = LoadMechanicQueries();

            retList.Add(toAdd);

            MemoryStream streamOut = new MemoryStream();

            try
            {
                querySerializer.WriteObject(streamOut, retList);
            } catch (SerializationException)
            {
                return(false);
            }
            BitWriter writerOut = new BitWriter(
                new FileStream(MechanicQueryFilePath, FileMode.Create, FileAccess.Write)
                );

            streamOut = new MemoryStream(streamOut.ToArray());
            AnsBlockEncoder encoder = new AnsBlockEncoder(1048576, writerOut);

            encoder.EncodeStream(streamOut, 8);
            writerOut.Flush();
            writerOut.Close();
            return(true);
        }
Exemplo n.º 2
0
        bool ICustomSerialization.Serialize(BinarySerializer Serializer)
        {
            Serializer.Writer.Write(4u);

            Serializer.Writer.Write(StartFrame);
            Serializer.Writer.Write(EndFrame);

            Serializer.Writer.Write((byte)PreRepeat);
            Serializer.Writer.Write((byte)PostRepeat);

            Serializer.Writer.Write((ushort)0);

            Serializer.Writer.Write(4u);

            BitWriter BW = new BitWriter(Serializer.Writer);

            foreach (bool Value in Values)
            {
                BW.WriteBit(Value);
            }

            BW.Flush();

            return(true);
        }
        /**
         * <summary>Attempts to add the KeywordTrainingExample specified by toAdd to the file KeywordDataFilePath</summary>
         * <param name="ex">KeywordTrainingExample to add</param>
         */
        public bool AddKeywordExample(KeywordTrainingExample ex)
        {
            DataContractJsonSerializer querySerializer = new DataContractJsonSerializer(
                typeof(List <KeywordTrainingExample>)
                );
            List <KeywordTrainingExample> retList = LoadKeywordTrainingExamples();

            retList.Add(ex);

            MemoryStream streamOut = new MemoryStream();

            try
            {
                querySerializer.WriteObject(streamOut, retList);
            }
            catch (SerializationException)
            {
                return(false);
            }
            BitWriter writerOut = new BitWriter(
                new FileStream(KeywordDataFilePath, FileMode.Create, FileAccess.Write)
                );

            streamOut = new MemoryStream(streamOut.ToArray());
            AnsBlockEncoder encoder = new AnsBlockEncoder(1048576, writerOut);

            encoder.EncodeStream(streamOut, 8);
            writerOut.Flush();
            writerOut.Close();
            return(true);
        }
 protected override void When()
 {
     _writer.Write(false);
     _writer.Write(true);
     _writer.Write(false);
     _writer.Write(true);
     _writer.Flush();
 }
Exemplo n.º 5
0
        public void Encode(Stream input, Stream output)
        {
            var bitLayoutStream         = new MemoryStream();
            var compressedTableStream   = new MemoryStream();
            var uncompressedTableStream = new MemoryStream();

            using var bitLayoutWriter = new BitWriter(bitLayoutStream, BitOrder.MostSignificantBitFirst, 1, ByteOrder.BigEndian);
            using var bwCompressed    = new BinaryWriter(compressedTableStream, Encoding.ASCII, true);
            using var bwUncompressed  = new BinaryWriter(uncompressedTableStream, Encoding.ASCII, true);

            var matches = _matchParser.ParseMatches(input);

            foreach (var match in matches)
            {
                // Write any data before the match, to the uncompressed table
                while (input.Position < match.Position)
                {
                    bitLayoutWriter.WriteBit(1);
                    bwUncompressed.Write((byte)input.ReadByte());
                }

                // Write match data to the compressed table
                var firstByte  = (byte)((match.Displacement - 1) >> 8);
                var secondByte = (byte)(match.Displacement - 1);

                if (match.Length < 0x12)
                {
                    // Since minimum _length should be 3 for Yay0, we get a minimum matchLength of 1 in this case
                    firstByte |= (byte)((match.Length - 2) << 4);
                }
                else
                {
                    // Yes, we do write the _length for a match into the uncompressed data stream, if it's >=0x12
                    bwUncompressed.Write((byte)(match.Length - 0x12));
                }

                bitLayoutWriter.WriteBit(0);
                bwCompressed.Write(firstByte);
                bwCompressed.Write(secondByte);

                input.Position += match.Length;
            }

            // Write any data after last match, to the uncompressed table
            while (input.Position < input.Length)
            {
                bitLayoutWriter.WriteBit(1);
                bwUncompressed.Write((byte)input.ReadByte());
            }

            bitLayoutWriter.Flush();

            WriteCompressedData(input, output, bitLayoutStream, compressedTableStream, uncompressedTableStream);
        }
Exemplo n.º 6
0
        public void GetLastByte_Writes4Bits_CompleteByte()
        {
            MemoryStream stream = new MemoryStream();
            var          writer = new BitWriter(stream);

            writer.Write(true);
            writer.Write(true);
            writer.Write(true);
            writer.Write(true);
            writer.Flush();
            Assert.AreEqual(240, stream.ToArray()[0]);
        }
Exemplo n.º 7
0
        public void TestFlushAndContinue()
        {
            var stream = new MemoryStream();
            var writer = new BitWriter(stream);

            writer.WriteBits(2, 3); // 01010[1101]10
            Assert.That(writer.Position, Is.EqualTo(2));

            writer.Flush();
            Assert.That(writer.Position, Is.EqualTo(2));

            var bytes = stream.ToArray();

            Assert.That(bytes, Is.EqualTo(new byte[] { 0xC0 }));

            writer.WriteBits(4, 6);
            writer.Flush();
            Assert.That(writer.Position, Is.EqualTo(6));

            bytes = stream.ToArray();
            Assert.That(bytes, Is.EqualTo(new byte[] { 0xD8 })); // 11 0110 00
        }
Exemplo n.º 8
0
        public void Should_write_bits_to_a_stream(string input, byte[] result)
        {
            var stream    = new MemoryStream();
            var bitWriter = new BitWriter(stream);

            WriteAllBits(bitWriter, input);
            bitWriter.Flush();

            stream.ToArray()
            .Should()
            .HaveCount(result.Length)
            .And.ContainInOrder(result);
        }
Exemplo n.º 9
0
 public void ReadBitsLHTest(BigInteger value, int length)
 {
     using (MemoryStream memory = new MemoryStream())
         using (BitWriter writer = new BitWriter(memory))
         {
             writer.WriteBitsLowToHigh(value, length);
             writer.Flush();
             memory.Seek(0, SeekOrigin.Begin);
             using (var reader = new BitReader(memory))
             {
                 Assert.AreEqual(value, reader.ReadBitsLowToHigh(length));
             }
         }
 }
Exemplo n.º 10
0
        public void Compress(Stream input, Stream output)
        {
            if (!_isCompressable)
            {
                throw new InvalidOperationException("This instance doesn't allow for compression.");
            }

            var inputArray = input.ToArray();

            // Obfuscate the data
            var obfuscator = CreateObfuscator(_obfuscationMode);

            if (obfuscator != null)
            {
                output.Position = 0;
                obfuscator.Obfuscate(inputArray);
                output.Position = 0;
            }

            // Find all Lz matches
            var matches = FindMatches(new MemoryStream(inputArray), _compressionMode, _huffmanMode);

            // Create huffman tree and value writer based on match filtered values
            var huffmanInput = RemoveMatchesFromInput(inputArray, matches);
            var tree         = CreateHuffmanTree(huffmanInput, _huffmanMode);
            var valueWriter  = CreateValueWriter(_huffmanMode, tree);

            using (var bw = new BitWriter(output, BitOrder.MostSignificantBitFirst, 4, ByteOrder.LittleEndian))
            {
                // Write header data
                bw.WriteBits((int)input.Length, 0x18);
                bw.WriteByte(0x70);

                var identByte = _compressionMode & 0x7;
                identByte |= (_huffmanMode & 0x3) << 3;
                identByte |= (_obfuscationMode & 0x7) << 5;
                bw.WriteByte(identByte);

                // Write huffman tree
                WriteHuffmanTree(bw, tree, _huffmanMode);

                // Encode the input data
                var encoder = CreateEncoder(_compressionMode, valueWriter);
                encoder.Encode(input, bw, matches);

                // Flush the buffer
                bw.Flush();
            }
        }
Exemplo n.º 11
0
        public void TestWriteBits32()
        {
            var stream = new MemoryStream();
            var writer = new BitWriter(stream);

            writer.WriteBits(3, 5); // 101
            writer.WriteBits(2, 1); // 01
            writer.WriteBits(27, 0x39B4DAC);
            Assert.That(writer.Position, Is.EqualTo(32));

            writer.Flush();
            var bytes = stream.ToArray();

            Assert.That(bytes, Is.EqualTo(new byte[] { 0xAB, 0x9B, 0x4D, 0xAC }));
        }
Exemplo n.º 12
0
        public void TestWriteBits16()
        {
            var stream = new MemoryStream();
            var writer = new BitWriter(stream);

            writer.WriteBits(3, 5);      // 101
            writer.WriteBits(2, 1);      // 01
            writer.WriteBits(11, 0x39B); // 011 1001 1011
            Assert.That(writer.Position, Is.EqualTo(16));

            writer.Flush();
            var bytes = stream.ToArray();

            Assert.That(bytes, Is.EqualTo(new byte[] { 0xAB, 0x9B }));
        }
Exemplo n.º 13
0
        public void TestWriteBits9()
        {
            var stream = new MemoryStream();
            var writer = new BitWriter(stream);

            writer.WriteBits(3, 5); // 101
            writer.WriteBits(2, 1); // 01
            writer.WriteBits(4, 3); // 0011
            Assert.That(writer.Position, Is.EqualTo(9));

            writer.Flush();
            var bytes = stream.ToArray();

            Assert.That(bytes, Is.EqualTo(new byte[] { 0xA9, 0x80 }));
        }
Exemplo n.º 14
0
        public void TestWriteBits24()
        {
            var stream = new MemoryStream();
            var writer = new BitWriter(stream);

            writer.WriteBits(3, 5);       // 101
            writer.WriteBits(2, 1);       // 01
            writer.WriteBits(13, 0x1A74); // 1 1010 0111 0100
            writer.WriteBits(6, 19);      // 010011
            Assert.That(writer.Position, Is.EqualTo(24));

            writer.Flush();
            var bytes = stream.ToArray();

            Assert.That(bytes, Is.EqualTo(new byte[] { 0xAE, 0x9D, 0x13 }));
        }
Exemplo n.º 15
0
        public void Test2()
        {
            using (var ms = new MemoryStream())
                using (var writer = new BitWriter(ms))
                {
                    writer.WriteBits(0b1, 1);
                    writer.WriteBits(0b10010, 5);
                    writer.WriteBits(0b10110011010111, 14);
                    writer.WriteBits(0b1000, 4);
                    writer.Flush();

                    var data   = ms.GetBuffer();
                    var reader = new BitReader(data);
                    Assert.AreEqual(0b100010110011010111100101, reader.ReadBits(24));
                }
        }
Exemplo n.º 16
0
        private static void RoundTrip <T>(Action <BitWriter> writerAction, Func <BitReader, T> readerAction, T expected)
        {
            using (var ms = new MemoryStream())
            {
                var writer = new BitWriter(ms);
                writerAction(writer);
                writer.Flush();
                ms.Seek(0, SeekOrigin.Begin);

                var buffer = new byte[ms.Length];
                ms.Read(buffer, 0, buffer.Length);
                var reader = new BitReader(buffer);
                var actual = readerAction(reader);

                Assert.Equal(expected, actual);
            }
        }
Exemplo n.º 17
0
        public void Test1()
        {
            using (var ms = new MemoryStream())
                using (var writer = new BitWriter(ms))
                {
                    writer.WriteBits(0b110, 3);
                    writer.WriteBits(0b01000, 5);
                    writer.WriteBits(0b01, 2);
                    writer.WriteBits(0b1110100, 7);
                    writer.Flush();

                    var data = ms.GetBuffer();
                    Assert.AreEqual(0b01000110, data[0]);
                    Assert.AreEqual(0b11010001, data[1]);
                    Assert.AreEqual(0b1, data[2]);
                }
        }
Exemplo n.º 18
0
        public void Read()
        {
            uint value     = 0x12345678;
            var  rand      = new Random(42);
            int  totalBits = 8 * ByteCount;
            int  writeBits = 0;
            var  bitWriter = new BitWriter(data, HigherOrderFirst);

            int bitCount = rand.Next(1, 32);

            while ((writeBits + bitCount) <= totalBits)
            {
                bitWriter.Write(value, bitCount);
                writeBits += bitCount;
                bitCount   = rand.Next(1, 32);
            }

            bitWriter.Flush();
        }
Exemplo n.º 19
0
        public void TestPartialFlushWhenPositionChanges()
        {
            var stream = new MemoryStream();
            var writer = new BitWriter(stream);

            writer.WriteBits(11, 0x2B6); // 01010[1101]10
            Assert.That(writer.Position, Is.EqualTo(11));

            writer.Position = 5;
            Assert.That(writer.Position, Is.EqualTo(5));

            writer.WriteBits(4, 6); // 0110 => 01010 0110 10
            Assert.That(writer.Position, Is.EqualTo(9));

            writer.Flush();
            var bytes = stream.ToArray();

            Assert.That(bytes, Is.EqualTo(new byte[] { 0x53, 0x40 })); // 0101 0011 0100 0000
        }
Exemplo n.º 20
0
        public void Encode(Stream input, Stream output)
        {
            var bitLayoutStream         = new MemoryStream();
            var compressedTableStream   = new MemoryStream();
            var uncompressedTableStream = new MemoryStream();

            using var bitLayoutWriter = new BitWriter(bitLayoutStream, BitOrder.MsbFirst, 1, ByteOrder.BigEndian);
            using var bwCompressed    = new BinaryWriter(compressedTableStream, Encoding.ASCII, true);
            using var bwUncompressed  = new BinaryWriter(uncompressedTableStream, Encoding.ASCII, true);

            var matches = _matchParser.ParseMatches(input);

            foreach (var match in matches)
            {
                // Write any data before the match, to the uncompressed table
                while (input.Position < match.Position)
                {
                    bitLayoutWriter.WriteBit(1);
                    bwUncompressed.Write((byte)input.ReadByte());
                }

                // Write match data to the compressed table
                var firstByte  = (byte)((byte)((match.Length - 3) << 4) | (byte)((match.Displacement - 1) >> 8));
                var secondByte = (byte)(match.Displacement - 1);
                bitLayoutWriter.WriteBit(0);
                bwCompressed.Write(firstByte);
                bwCompressed.Write(secondByte);

                input.Position += match.Length;
            }

            // Write any data after last match, to the uncompressed table
            while (input.Position < input.Length)
            {
                bitLayoutWriter.WriteBit(1);
                bwUncompressed.Write((byte)input.ReadByte());
            }

            bitLayoutWriter.Flush();

            WriteCompressedData(input, output, bitLayoutStream, compressedTableStream, uncompressedTableStream);
        }
Exemplo n.º 21
0
        private void WriteImage2()
        {
            Logger.Trace("Writing image...");

            using (var context = _image.CreateUnsafeContext())
            //using (var context = _image)
            {
                for (var y = 0; y < _height; y++)
                {
                    var rowData      = new byte[_rowLengthInBytes];
                    var memoryStream = new MemoryStream(rowData);
                    var bitWriter    = new BitWriter(memoryStream);
                    for (var x = 0; x < _width; x++)
                    {
                        try
                        {
                            var color = context.GetPixel(x, y);
                            bitWriter.Write(color.G);
                            bitWriter.Write(color.R);
                            bitWriter.Write(color.A);
                            bitWriter.Write(color.B);

                            //bitWriter.Write(color.B);
                            //bitWriter.Write(color.G);
                            //bitWriter.Write(color.R);
                            //bitWriter.Write(color.A);

                            //_writer.Write(color.B);
                            //_writer.Write(color.G);
                            //_writer.Write(color.R);
                            //_writer.Write(color.A);
                        }
                        catch (Exception)
                        {
                        }
                    }

                    bitWriter.Flush();
                    _writer.Write(rowData);
                }
            }
        }
Exemplo n.º 22
0
 public void ReadEnumLHTest()
 {
     using (MemoryStream memory = new MemoryStream())
         using (BitWriter writer = new BitWriter(memory))
         {
             writer.WriteEnumLowToHigh(TestEnum.Value0);
             writer.WriteEnumLowToHigh(TestEnum.Value1);
             writer.WriteEnumLowToHigh(TestEnum.Value2);
             writer.WriteEnumLowToHigh(TestEnum.Value3);
             writer.Flush();
             memory.Seek(0, SeekOrigin.Begin);
             using (var reader = new BitReader(memory))
             {
                 Assert.AreEqual(TestEnum.Value0, reader.ReadEnumLowToHigh <TestEnum>());
                 Assert.AreEqual(TestEnum.Value1, reader.ReadEnumLowToHigh <TestEnum>());
                 Assert.AreEqual(TestEnum.Value2, reader.ReadEnumLowToHigh <TestEnum>());
                 Assert.AreEqual(TestEnum.Value3, reader.ReadEnumLowToHigh <TestEnum>());
             }
         }
 }
Exemplo n.º 23
0
        private void WriteImage32()
        {
            Logger.Trace("Writing image...");

            using (UnsafeBitmapContext unsafeContext = _image.CreateUnsafeContext())
            {
                for (int y = 0; y < _height; ++y)
                {
                    byte[] buffer = new byte[_rowLengthInBytes];

                    BitWriter bitWriter = new BitWriter(new MemoryStream(buffer));

                    for (int x = 0; x < _width; ++x)
                    {
                        Color pixel = unsafeContext.GetPixel(x, y);

                        pixel.ToArgb();

                        byte alpha = (byte)(byte.MaxValue - (uint)pixel.A);

                        if (!Reader.IsVerge)
                        {
                            bitWriter.WriteBits(pixel.R, 8);
                            bitWriter.WriteBits(pixel.G, 8);
                            bitWriter.WriteBits(pixel.B, 8);
                            bitWriter.WriteBits((byte)(0xff - alpha), 8);
                        }
                        else
                        {
                            bitWriter.WriteBits(pixel.B, 8);
                            bitWriter.WriteBits(pixel.G, 8);
                            bitWriter.WriteBits(pixel.R, 8);
                            bitWriter.WriteBits((byte)(0xff - alpha), 8);
                        }
                    }

                    bitWriter.Flush();
                    _writer.Write(buffer);
                }
            }
        }
            public void ShouldBeAbleEmbedAndExtractPayload(string targetBinaryString, string payloadBinaryString, string expectedBinaryString)
            {
                var target = Utils.FromBinaryString(targetBinaryString).First();

                using var payload = Utils.FromBinaryString(payloadBinaryString).ToStream();

                _sut.Embed(ref target, new BitReader(payload, includeLengthHeader: false));

                target.ToBinaryString().Should().Be(expectedBinaryString);

                using var outputStream = new MemoryStream();
                var payloadWriter = new BitWriter(outputStream, contentIncludesLengthHeader: false);

                _sut.Extract(target, payloadWriter);

                payloadWriter.Flush();

                var actualPayload = outputStream.ToArray().First();

                actualPayload.ToBinaryString().Should().Be(payloadBinaryString);
            }
        private void WriteInitialFiles()
        {
            byte[]       memoryStore = new byte[] { 91, 93 };
            MemoryStream toWrite     = new MemoryStream(memoryStore);
            BitWriter    writerOut   = new BitWriter(
                new FileStream(KeywordDataFilePath, FileMode.Create, FileAccess.Write)
                );
            AnsBlockEncoder encoder = new AnsBlockEncoder(1048576, writerOut);

            encoder.EncodeStream(toWrite, 8);
            writerOut.Flush();
            writerOut.Close();
            toWrite   = new MemoryStream(memoryStore);
            writerOut = new BitWriter(
                new FileStream(MechanicQueryFilePath, FileMode.Create, FileAccess.Write)
                );
            encoder = new AnsBlockEncoder(1048576, writerOut);
            encoder.EncodeStream(toWrite, 8);
            writerOut.Flush();
            writerOut.Close();
        }
Exemplo n.º 26
0
        private void WriteImage()
        {
            Logger.Trace("写入图像...");

            var  paletteHash = new Dictionary <Color, byte>();
            byte i           = 0;

            foreach (var color in _palette)
            {
                paletteHash[color] = i;
                i++;
            }

            using (var context = _image.CreateUnsafeContext())
            {
                for (var y = 0; y < _height; y++)
                {
                    var rowData      = new byte[_rowLengthInBytes];
                    var memoryStream = new MemoryStream(rowData);
                    var bitWriter    = new BitWriter(memoryStream);
                    for (var x = 0; x < _width; x++)
                    {
                        var color = context.GetPixel(x, y);
                        if (color.A < 0x80 && _transparency == 1)
                        {
                            bitWriter.WriteBits(0, _bitsPerPixel);
                        }
                        else
                        {
                            var paletteIndex = paletteHash[color];
                            bitWriter.WriteBits(paletteIndex, _bitsPerPixel);
                        }
                    }

                    bitWriter.Flush();
                    _writer.Write(rowData);
                }
            }
        }
        public void EncodeStream(Stream streamIn, byte numberBitsPerSymbol, int targetDenominator = -1)
        {
            BitReader readerIn = new BitReader(streamIn);
            long      pos      = Output.Output.Position;

            Output.WriteByte(0);
            Output.WriteByte(0);
            Output.WriteByte(0);
            int testByte = readerIn.ReadInt(numberBitsPerSymbol);

            if (readerIn.EOF)
            {
                throw new EndOfStreamException("Stream ended before numberBitsPerSymbol bits were read. This is not worth encoding.");
            }
            int numBlocks = 0;

            while (!readerIn.EOF)
            {
                int numReadBytes = readerIn.ReadInts(Block, 1, Block.Length - 1, numberBitsPerSymbol);
                Block[0] = testByte;
                testByte = readerIn.ReadInt(numberBitsPerSymbol);
                if (readerIn.EOF && readerIn.WereBitsReadOnEOF)
                {
                    int[] newBlock = new int[Block.Length + 1];
                    Block.CopyTo(newBlock, 0);
                    newBlock[Block.Length] = testByte;
                    EncodeBlock(numReadBytes + 2, targetDenominator);
                }
                else
                {
                    EncodeBlock(numReadBytes + 1, targetDenominator);
                }
                numBlocks++;
            }
            Output.Flush();
            Output.Output.Seek(pos, SeekOrigin.Begin);
            Output.WriteLong(numBlocks, 24);
        }
Exemplo n.º 28
0
        public void SimpleWriterTest()
        {
            const int  ByteCount        = 20;
            const bool HigherOrderFirst = true;

            byte[] data      = new byte[ByteCount];
            uint   value     = 0x12345678;
            var    rand      = new Random(42);
            int    totalBits = 8 * ByteCount;
            int    writeBits = 0;
            var    bitWriter = new BitWriter(data, HigherOrderFirst);

            int bitCount = rand.Next(1, 32);

            while ((writeBits + bitCount) <= totalBits)
            {
                bitWriter.Write(value, bitCount);
                writeBits += bitCount;
                bitCount   = rand.Next(1, 32);
            }

            bitWriter.Flush();
        }
Exemplo n.º 29
0
        public void RoundTripTest(int arrayLength, bool higherOrderBitsFirst)
        {
            var rand = new Random(42);

            byte[] input  = new byte[arrayLength];
            byte[] output = new byte[arrayLength];

            rand.NextBytes(input);

            int  totalBits       = arrayLength * 8;
            int  processedBits   = 0;
            int  nextProcessBits = rand.Next(1, 32);
            uint buffer          = 0;

            var reader = new BitReader(input, higherOrderBitsFirst);
            var writer = new BitWriter(output, higherOrderBitsFirst);

            while ((processedBits + nextProcessBits) <= totalBits)
            {
                buffer = (buffer << nextProcessBits) | reader.Read(nextProcessBits);
                writer.Write(buffer, nextProcessBits);
                processedBits  += nextProcessBits;
                nextProcessBits = rand.Next(1, 32);
            }

            if (processedBits < totalBits)
            {
                nextProcessBits = totalBits - processedBits;
                buffer          = (buffer << nextProcessBits) | reader.Read(nextProcessBits);
                writer.Write(buffer, nextProcessBits);
            }

            writer.Flush();

            Assert.True(input.AsSpan().SequenceEqual(output));
        }
Exemplo n.º 30
0
        public void TestWriteBit()
        {
            var stream = new MemoryStream();
            var writer = new BitWriter(stream);

            var values = new bool[]
            {
                true, false, true, false, false, false, true, true,
                false, true, true, true, true, true, true, false,
                true, false, false, false, false, false, false, true,
                true, true, true, true, false, false, true, false
            };

            for (int i = 0; i < 32; i++)
            {
                writer.WriteBit(values[i]);
                Assert.That(writer.Position, Is.EqualTo(i + 1), "after bit " + i);
            }

            writer.Flush();
            var bytes = stream.ToArray();

            Assert.That(bytes, Is.EqualTo(new byte[] { 0xA3, 0x7E, 0x81, 0xF2 }));
        }
Exemplo n.º 31
0
        private byte[] EncodeIntra(Bitmap Frame)
        {
            BitmapData d = Frame.LockBits(new Rectangle(0, 0, Frame.Width, Frame.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
            //Setup the macroblocks
            for (int y = 0; y < Height; y += 16)
            {
                for (int x = 0; x < Width; x += 16)
                {
                    MacroBlocks[y / 16][x / 16] = new MacroBlock(d, x, y);
                    Analyzer.ConfigureBlockY(this, MacroBlocks[y / 16][x / 16]);
                    int blocktype2 = Analyzer.AnalyzeBlockUV(this, MacroBlocks[y / 16][x / 16]);
                    MacroBlocks[y / 16][x / 16].UVPredictionMode = blocktype2;
                    MacroBlocks[y / 16][x / 16].UVUseComplex8x8[0] = true;
                    MacroBlocks[y / 16][x / 16].UVUseComplex8x8[1] = true;
                    MacroBlocks[y / 16][x / 16].SetupDCTs(this);
                }
            }
            Frame.UnlockBits(d);
            BitWriter b = new BitWriter();
            b.WriteBits(1, 1);//Interframe
            b.WriteBits(1, 1);//YUV format
            //TODO: determine table (when we actually use it...)
            b.WriteBits(0, 1);//Table
            b.WriteBits((uint)Quantizer, 6);//Quantizer
            for (int y = 0; y < Height; y += 16)
            {
                for (int x = 0; x < Width; x += 16)
                {
                    MacroBlock curblock = MacroBlocks[y / 16][x / 16];

                    //Todo use predicted prediction mode
                    /*if (x > 0 && y > 0)
                    {
                        int r12 = MacroBlocks[y / 16 - 1][x / 16].YPredictionMode;
                        int r6 = MacroBlocks[y / 16][x / 16 - 1].YPredictionMode;
                        if (r12 > r6) r12 = r6;
                        if (r12 == 9) r12 = 3;
                        r6 = r3 >> 28;
                        if (r6 >= r12) r6++;
                        int r7;
                        if (r6 < 9)
                        {
                            r12 = r6;
                            r7 = 4;
                        }
                        else r7 = 1;
                        r3 <<= r7;
                        nrBitsRemaining -= r7;
                    }*/


                    b.WriteBits(0, 1);//Func
                    EncodeBlockIntra(curblock, b);
                }
            }
            b.WriteBits(0, 16);
            b.Flush();
            byte[] result = b.ToArray();
            return result;
        }
Exemplo n.º 32
0
 private unsafe byte[] EncodePrediction(Bitmap Frame)
 {
     //We'll just look if there are blocks that are 100% the same first
     BitmapData d = Frame.LockBits(new Rectangle(0, 0, Frame.Width, Frame.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
     BitmapData prev = PastFrames[1].LockBits(new Rectangle(0, 0, Frame.Width, Frame.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
     for (int y = 0; y < Height; y += 16)
     {
         for (int x = 0; x < Width; x += 16)
         {
             MacroBlocks[y / 16][x / 16] = new MacroBlock(d, x, y);
             bool same = true;
             for (int y2 = 0; y2 < 16; y2++)
             {
                 ulong* pA = (ulong*)(((byte*)d.Scan0) + (y + y2) * d.Stride + x * 4);
                 ulong* pB = (ulong*)(((byte*)prev.Scan0) + (y + y2) * prev.Stride + x * 4);
                 for (int x2 = 0; x2 < 16; x2+=2)
                 {
                     ulong color = *pA++;
                     ulong color2 = *pB++;
                     if (color != color2)
                     {
                         same = false;
                         break;
                     }
                 }
                 if (!same) break;
             }
             if (same) MacroBlocks[y / 16][x / 16].Predict = true;
             else
             {
                 Analyzer.ConfigureBlockY(this, MacroBlocks[y / 16][x / 16]);
                 int blocktype2 = Analyzer.AnalyzeBlockUV(this, MacroBlocks[y / 16][x / 16]);
                 MacroBlocks[y / 16][x / 16].UVPredictionMode = blocktype2;
                 MacroBlocks[y / 16][x / 16].UVUseComplex8x8[0] = true;
                 MacroBlocks[y / 16][x / 16].UVUseComplex8x8[1] = true;
                 MacroBlocks[y / 16][x / 16].SetupDCTs(this);
             }
         }
     }
     Frame.UnlockBits(d);
     PastFrames[1].UnlockBits(prev);
     BitWriter b = new BitWriter();
     b.WriteBits(0, 1);//Interframe
     b.WriteVarIntSigned(0);
     for (int y = 0; y < Height; y += 16)
     {
         for (int x = 0; x < Width; x += 16)
         {
             MacroBlock curblock = MacroBlocks[y / 16][x / 16];
             if (curblock.Predict)
             {
                 b.WriteBits(1, 1);
                 b.WriteVarIntUnsigned(0);
             }
             else
             {
                 b.WriteBits(0xE >> 1, 5);
                 EncodeBlockIntra(curblock, b);
             }
         }
     }
     b.WriteBits(0, 16);
     b.Flush();
     byte[] result = b.ToArray();
     return result;
 }