System.IO.MemoryStream.WriteByte(byte)

Here are the examples of the csharp api System.IO.MemoryStream.WriteByte(byte) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

658 Examples 7

19 Source : PngByteQRCode.cs
with GNU General Public License v3.0
from BRH-Media

public void WritePalette(params byte[][] rgbaColors)
            {
                const int Red = 0, Green = 1, Blue = 2, Alpha = 3;
                const byte Opaque = 255;
                var hasAlpha = false;

                this.WriteChunkStart(PLTE, 3 * rgbaColors.Length);
                foreach (var color in rgbaColors)
                {
                    hasAlpha |= color.Length > Alpha && color[Alpha] < Opaque;
                    this.stream.WriteByte(color[Red]);
                    this.stream.WriteByte(color[Green]);
                    this.stream.WriteByte(color[Blue]);
                }
                this.WriteChunkEnd();

                if (!hasAlpha)
                {
                    return;
                }

                this.WriteChunkStart(tRNS, rgbaColors.Length);
                foreach (var color in rgbaColors)
                {
                    this.stream.WriteByte(color.Length > Alpha ? color[Alpha] : Opaque);
                }
                this.WriteChunkEnd();
            }

19 Source : PngByteQRCode.cs
with GNU General Public License v3.0
from BRH-Media

public void WriteHeader(int width, int height, byte bitDepth, ColorType colorType)
            {
                this.stream.Write(PngSignature, 0, PngSignature.Length);
                this.WriteChunkStart(IHDR, 13);

                // Size.
                this.WriteIntBigEndian((uint)width);
                this.WriteIntBigEndian((uint)height);

                // Color.
                this.stream.WriteByte(bitDepth);
                this.stream.WriteByte((byte)colorType);

                // Constants.
                this.stream.WriteByte(0);
                this.stream.WriteByte(0);
                this.stream.WriteByte(0);

                this.WriteChunkEnd();
            }

19 Source : PngByteQRCode.cs
with GNU General Public License v3.0
from BRH-Media

public void WriteScanlines(byte[] scanlines)
            {
                using (var idatStream = new MemoryStream())
                {
                    Deflate(idatStream, scanlines);

                    this.WriteChunkStart(IDAT, (int)(idatStream.Length + 6));

                    // Deflate header.
                    this.stream.WriteByte(0x78); // 8 Deflate algorithm, 7 max window size
                    this.stream.WriteByte(0x9C); // Check bits.

                    // Compressed data.
                    idatStream.Position = 0;
#if NET35
                    idatStream.WriteTo(this.stream);
#else
                    idatStream.CopyTo(this.stream);
#endif
                    // Deflate checksum.
                    var adler = Adler32(scanlines, 0, scanlines.Length);
                    this.WriteIntBigEndian(adler);

                    this.WriteChunkEnd();
                }
            }

19 Source : PngByteQRCode.cs
with GNU General Public License v3.0
from BRH-Media

private void WriteIntBigEndian(uint value)
            {
                this.stream.WriteByte((byte)(value >> 24));
                this.stream.WriteByte((byte)(value >> 16));
                this.stream.WriteByte((byte)(value >> 8));
                this.stream.WriteByte((byte)value);
            }

19 Source : CelesteExtractor.cs
with MIT License
from briangordon

private Texture2D LoadTextureFromStream(Stream inputStream) {
            byte[] textureDimensionsBytes = new byte[8];
            inputStream.Read(textureDimensionsBytes, 0, 8);
            int textureWidth = BitConverter.ToInt32(textureDimensionsBytes, 0);
            int textureHeight = BitConverter.ToInt32(textureDimensionsBytes, 4);
            bool isTransparent = Convert.ToBoolean(inputStream.ReadByte());

            using (MemoryStream outputStream = new MemoryStream()) {
                // The texture format uses a run-length encoding which allows the same 
                // bytes to represent data for multiple sequential pixels.
                int runLength;
                while ((runLength = inputStream.ReadByte()) != -1) {
                    byte o, b, g, r; // Opacity, Blue, Green, Red

                    if (isTransparent) {
                        o = (byte)inputStream.ReadByte();

                        if (o == 0) {
                            b = g = r = 0;
                        } else {
                            b = (byte)inputStream.ReadByte();
                            g = (byte)inputStream.ReadByte();
                            r = (byte)inputStream.ReadByte();
                        }
                    } else {
                        o = byte.MaxValue;
                        b = (byte)inputStream.ReadByte();
                        g = (byte)inputStream.ReadByte();
                        r = (byte)inputStream.ReadByte();
                    }

                    for (int i = 0; i < runLength; i++) {
                        outputStream.WriteByte(r);
                        outputStream.WriteByte(g);
                        outputStream.WriteByte(b);
                        outputStream.WriteByte(o);
                    }
                }

                Texture2D texture = new Texture2D(graphicsDevice, textureWidth, textureHeight);
                texture.SetData<byte>(outputStream.GetBuffer(), 0, (int)outputStream.Length);
                return texture;
            }
        }

19 Source : TestableILRecompiler.cs
with MIT License
from bryanperris

public void Init(TestCase tester)
        {
            m_TestCase = tester;

            BypreplacedMMU = true;
            //AttachIStream(new StreamEx.Wrapper(cor64.DataEndianess.PreByteSwapStream(tester.GetProgram(), cor64.Cartridge.RomEndianess.Big)));
            AttachIStream(tester.GetProgram());
			AttachDStream(m_TestDataMemory);

            /* Inject zeros into data memory */
            for (int i = 0; i < 16; i++)
            {
                m_TestDataMemory.WriteByte(0);
            }

            if (m_TestCase.IsXfer)
            {
                InjectXferSource(tester);
                return;
            }

            if (m_TestCase.IsLoadStore && m_TestCase.InjectDMem)
            {
                Stream s = m_TestDataMemory;

                //switch (m_TestCase.ExpectedBytes.Length)
                //{
                //    default: break;
                //    case 2: s = new Swap16Stream(s); break;
                //    case 4: s = new Swap32Stream(s); break;
                //    case 8: s = new Swap64Stream(s); break;
                //}

                s.Position = m_TestCase.ExepectedBytesOffset;
                s.Write(m_TestCase.ExpectedBytes, 0, m_TestCase.ExpectedBytes.Length);
            }

            if (!m_TestCase.IsFpuTest)
            {

                if (tester.SourceA.Key >= 0)
                    WriteGPR64(tester.SourceA.Key, (ulong)tester.SourceA.Value);

                if (!tester.IsImmediate && tester.SourceB.Key >= 0)
                {
                    WriteGPR64(tester.SourceB.Key, (ulong)tester.SourceB.Value);
                }
            }
            else
            {
                if (tester.SourceA.Key >= 0)
                {
                    SetFPRValue(tester.SourceA.Key, tester.SourceA.Value);
                }

                if (tester.SourceB.Key >= 0)
                {
                    SetFPRValue(tester.SourceB.Key, tester.SourceB.Value);
                }
            }
        }

19 Source : TestableInterpreter.cs
with MIT License
from bryanperris

public void Init(TestCase tester)
        {
            m_TestCase = tester;

            BypreplacedMMU = true;
            //AttachIStream(new StreamEx.Wrapper(cor64.DataEndianess.PreByteSwapStream(tester.GetProgram(), cor64.Cartridge.RomEndianess.Big)));
            AttachIStream(tester.GetProgram());
			AttachDStream(m_TestDataMemory);

            Cop0.REGS.Status.SetFRMode(tester.UseFPUHalfMode);

            /* Inject zeros into data memory */
            for (int i = 0; i < 16; i++)
            {
                m_TestDataMemory.WriteByte(0);
            }

            if (m_TestCase.IsXfer)
            {
                InjectXferSource(tester);
                return;
            }

            if (m_TestCase.IsLoadStore && m_TestCase.InjectDMem)
            {
                Stream s = m_TestDataMemory;

                //switch (m_TestCase.ExpectedBytes.Length)
                //{
                //    default: break;
                //    case 2: s = new Swap16Stream(s); break;
                //    case 4: s = new Swap32Stream(s); break;
                //    case 8: s = new Swap64Stream(s); break;
                //}

                s.Position = m_TestCase.ExepectedBytesOffset;
                s.Write(m_TestCase.ExpectedBytes, 0, m_TestCase.ExpectedBytes.Length);
            }

            if (!m_TestCase.IsFpuTest)
            {

                if (tester.SourceA.Key >= 0)
                    WriteGPR64(tester.SourceA.Key, (ulong)tester.SourceA.Value);

                if (!tester.IsImmediate && tester.SourceB.Key >= 0)
                {
                    WriteGPR64(tester.SourceB.Key, (ulong)tester.SourceB.Value);
                }
            }
            else
            {
                if (tester.SourceA.Key >= 0)
                {
                    SetFPRValue(tester.SourceA.Key, tester.SourceA.Value);
                }

                if (tester.SourceB.Key >= 0)
                {
                    SetFPRValue(tester.SourceB.Key, tester.SourceB.Value);
                }
            }
        }

19 Source : TraceLogTests.cs
with MIT License
from bryanperris

private static void ExpectTraceLog(AsmBlock[] asmBlocks, String[] expectedTrace = null) {
            BreplacedSymbolSource symbolSource = null;

            MemoryStream mem = new MemoryStream
            {
                Position = 0
            };

            foreach (var block in from b in asmBlocks orderby b.Address select b) {
                var asmStream = Asm.replacedemble(ref symbolSource, block.Code);
                asmStream.Position = 0;

                for (var i = mem.Position; i < block.Address; i++) {
                    mem.WriteByte(0);
                }

                asmStream.CopyTo(mem);
            }

            var core = BuildTraceableCore(mem, 0);
            var tracer = core.TraceLog;

            core.Disreplacedembler.AttachSymbolProvider(symbolSource);

            if (expectedTrace == null)
                tracer.EnableLogVerfication();

            var stepsTaken = 1;

            while (!core.InfiniteLoopWarn) {
                core.Step();
                stepsTaken++;
            }

            /* Trace the delay slot */
            core.Step();

            tracer.StoppedAt = core.ReadPC() + 4;
            var traceLog = tracer.GenerateTraceLog();

            if (expectedTrace == null) {
                expectedTrace = tracer.TestLog.ToArray();

                // Filter out real log comments
                traceLog = (from l in traceLog.ToList() where !l.StartsWith("/*") select l).ToList();
                traceLog = (from l in traceLog.ToList() where !l.EndsWith("~") select l).ToList();
            }

            String expectedStr = LinesToString(expectedTrace);
            String actualStr = LinesToString(traceLog);

            Console.WriteLine("Expected: \n" + expectedStr);
            Console.WriteLine("Actual: \n" + actualStr);
            Console.WriteLine("Core Steps Taken: {0}", stepsTaken);

            replacedert.AreEqual(expectedTrace.Length, traceLog.Count);

            for (int i = 0; i < expectedTrace.Length; i++) {
                var expectedLine = expectedTrace[i];
                var traceLine = traceLog[i].Replace("\r", "");

                if (traceLine.IndexOf('/') > 0) {
                    traceLine = traceLine.Substring(0, traceLine.IndexOf('/') + 1);
                    traceLine = traceLine.Trim();
                }

                replacedert.AreEqual(expectedLine, traceLine);
            }
        }

19 Source : N64Assembler.cs
with MIT License
from bryanperris

public void WriteBE(ulong data, int len)
            {
                var shift = 8 * len;

                while (len > 0)
                {
                    len--;
                    shift -= 8;
                    m_OutputStream.WriteByte((byte)(data >> shift));
                }

            }

19 Source : N64Assembler.cs
with MIT License
from bryanperris

public void WriteLE(ulong data, int len)
            {
                while (len > 0)
                {
                    len--;
                    m_OutputStream.WriteByte((byte)data);
                    data >>= 8;
                }
            }

19 Source : PdfString.cs
with Apache License 2.0
from cajuncoding

internal static byte[] ToPdfLiteral(byte[] preamble, byte[] data)
        {
            // We size the memory stream to be slighly larger than
            // encodedString to account for the enclosing parentheses
            // and the possiblilty of escaped characters.
            MemoryStream ms = new MemoryStream(data.Length + 10);

            // 0x28 == '('
            // 0x29 == ')'
            // 0x5c == '\'
            // 0x0a == LF
            // 0x0d == CR

            // CR and LF characters are also escaped to prevent them from being normalised.

            ms.WriteByte(0x28);
            ms.Write(preamble, 0, preamble.Length);
            for (int x = 0; x < data.Length; x++)
            {
                byte b = data[x];
                if (b == 0x28 || b == 0x29 || b == 0x5c)
                {
                    ms.WriteByte(0x5c);
                    ms.WriteByte(b);
                }
                else if (b == 0x0d)
                {
                    ms.WriteByte(0x5c);
                    ms.WriteByte(0x72); // 'r'
                }
                else if (b == 0x0a)
                {
                    ms.WriteByte(0x5c);
                    ms.WriteByte(0x6e); // 'n'
                }
                else
                {
                    ms.WriteByte(b);
                }
            }
            ms.WriteByte(0x29);

            return ms.ToArray();
        }

19 Source : FlateFilter.cs
with Apache License 2.0
from cajuncoding

public byte[] Encode(byte[] data)
        {
            MemoryStream ms = new MemoryStream(data.Length);
            ms.WriteByte(0x78); // ZLib Header for compression level 3.
            ms.WriteByte(0x5e);
            DeflateStream ds = new DeflateStream(ms, CompressionMode.Compress);
            ds.Write(data, 0, data.Length);
            ds.Close();
            return ms.ToArray();
        }

19 Source : PdfString.cs
with Apache License 2.0
from cajuncoding

internal static byte[] ToPdfHexadecimal(byte[] preamble, byte[] data)
        {
            // Each input byte expands to two output bytes.
            MemoryStream ms = new MemoryStream(data.Length * 2 + 2);

            // 0x3c == '<'
            // 0x3e == '>'

            ms.WriteByte(0x3c);
            ms.Write(preamble, 0, preamble.Length);
            for (int x = 0; x < data.Length; x++)
            {
                byte b = data[x];
                ms.WriteByte(HexDigits[b >> 4]);
                ms.WriteByte(HexDigits[b & 0x0f]);
            }
            ms.WriteByte(0x3e);

            return ms.ToArray();
        }

19 Source : HttpUtility.cs
with GNU General Public License v2.0
from Cdorey

internal static string InternalUrlDecode (
      byte[] bytes, int offset, int count, Encoding encoding)
    {
      var output = new StringBuilder ();
      using (var acc = new MemoryStream ()) {
        var end = count + offset;
        for (var i = offset; i < end; i++) {
          if (bytes[i] == '%' && i + 2 < count && bytes[i + 1] != '%') {
            int xchar;
            if (bytes[i + 1] == (byte) 'u' && i + 5 < end) {
              if (acc.Length > 0) {
                output.Append (getChars (acc, encoding));
                acc.SetLength (0);
              }

              xchar = getChar (bytes, i + 2, 4);
              if (xchar != -1) {
                output.Append ((char) xchar);
                i += 5;

                continue;
              }
            }
            else if ((xchar = getChar (bytes, i + 1, 2)) != -1) {
              acc.WriteByte ((byte) xchar);
              i += 2;

              continue;
            }
          }

          if (acc.Length > 0) {
            output.Append (getChars (acc, encoding));
            acc.SetLength (0);
          }

          if (bytes[i] == '+') {
            output.Append (' ');
            continue;
          }

          output.Append ((char) bytes[i]);
        }

        if (acc.Length > 0)
          output.Append (getChars (acc, encoding));
      }

      return output.ToString ();
    }

19 Source : HttpUtility.cs
with GNU General Public License v2.0
from Cdorey

internal static byte[] InternalUrlDecodeToBytes (byte[] bytes, int offset, int count)
    {
      using (var res = new MemoryStream ()) {
        var end = offset + count;
        for (var i = offset; i < end; i++) {
          var c = (char) bytes[i];
          if (c == '+') {
            c = ' ';
          }
          else if (c == '%' && i < end - 2) {
            var xchar = getChar (bytes, i + 1, 2);
            if (xchar != -1) {
              c = (char) xchar;
              i += 2;
            }
          }

          res.WriteByte ((byte) c);
        }

        res.Close ();
        return res.ToArray ();
      }
    }

19 Source : ModbusAsciiTransport.cs
with Apache License 2.0
from cdy816

internal override byte[] BuildMessageFrame(IModbusMessage message)
        {
            var msgFrame = message.MessageFrame;

            var msgFrameAscii = ModbusUtility.GetAsciiBytes(msgFrame);
            var lrcAscii = ModbusUtility.GetAsciiBytes(ModbusUtility.CalculateLrc(msgFrame));
            var nlAscii = Encoding.UTF8.GetBytes(Modbus.NewLine.ToCharArray());

            var frame = new MemoryStream(1 + msgFrameAscii.Length + lrcAscii.Length + nlAscii.Length);
            frame.WriteByte((byte)':');
            frame.Write(msgFrameAscii, 0, msgFrameAscii.Length);
            frame.Write(lrcAscii, 0, lrcAscii.Length);
            frame.Write(nlAscii, 0, nlAscii.Length);

            return frame.ToArray();
        }

19 Source : ModbusIpTransport.cs
with Apache License 2.0
from cdy816

internal static byte[] GetMbapHeader(IModbusMessage message)
        {
            byte[] transactionId = BitConverter.GetBytes(IPAddress.HostToNetworkOrder((short)message.TransactionId));
            byte[] length = BitConverter.GetBytes(IPAddress.HostToNetworkOrder((short)(message.ProtocolDataUnit.Length + 1)));

            var stream = new MemoryStream(7);
            stream.Write(transactionId, 0, transactionId.Length);
            stream.WriteByte(0);
            stream.WriteByte(0);
            stream.Write(length, 0, length.Length);
            stream.WriteByte(message.SlaveAddress);

            return stream.ToArray();
        }

19 Source : ModbusIpTransport.cs
with Apache License 2.0
from cdy816

internal static byte[] GetMbapHeader(IModbusMessage message)
        {
            byte[] transactionId = BitConverter.GetBytes(IPAddress.HostToNetworkOrder((short)message.TransactionId));
            byte[] length = BitConverter.GetBytes(IPAddress.HostToNetworkOrder((short)(message.ProtocolDataUnit.Length + 1)));

            var stream = new MemoryStream(7);
            stream.Write(transactionId, 0, transactionId.Length);
            stream.WriteByte(0);
            stream.WriteByte(0);
            stream.Write(length, 0, length.Length);
            stream.WriteByte(message.SlaveAddress);

            return stream.ToArray();
        }

19 Source : PostData.cs
with MIT License
from CefNet

public void AddAsUrlEncoded(string name, string value)
		{
			if (!_content.CanWrite)
				throw new InvalidOperationException();

			if (string.IsNullOrWhiteSpace(name))
				throw new ArgumentOutOfRangeException(nameof(name));

			byte[] buffer;
			if (_content.Position > 0)
			{
				_content.WriteByte((byte)'&');
			}
			name = Uri.EscapeDataString(name);
			buffer = Encoding.GetBytes(name);
			_content.Write(buffer, 0, buffer.Length);
			if (value != null)
			{
				_content.WriteByte((byte)'=');
				value = Uri.EscapeDataString(value);
				buffer = Encoding.GetBytes(value);
				_content.Write(buffer, 0, buffer.Length);
			}
		}

19 Source : SerializationUtils.cs
with Apache License 2.0
from census-instrumentation

internal static byte[] SerializeBinary(ITagContext tags)
        {
            // Use a ByteArrayDataOutput to avoid needing to handle IOExceptions.
            // ByteArrayDataOutput byteArrayDataOutput = ByteStreams.newDataOutput();
            MemoryStream byteArrayDataOutput = new MemoryStream();

            byteArrayDataOutput.WriteByte(VersionId);
            int totalChars = 0; // Here chars are equivalent to bytes, since we're using ascii chars.
            foreach (var tag in tags)
            {
                totalChars += tag.Key.Name.Length;
                totalChars += tag.Value.replacedtring.Length;
                EncodeTag(tag, byteArrayDataOutput);
            }

            // for (Iterator<Tag> i = InternalUtils.getTags(tags); i.hasNext();) {
            //    Tag tag = i.next();
            //    totalChars += tag.getKey().getName().length();
            //    totalChars += tag.getValue().replacedtring().length();
            //    encodeTag(tag, byteArrayDataOutput);
            // }
            if (totalChars > TagContextSerializedSizeLimit)
            {
                throw new TagContextSerializationException(
                    "Size of TagContext exceeds the maximum serialized size "
                        + TagContextSerializedSizeLimit);
            }

            return byteArrayDataOutput.ToArray();
        }

19 Source : SerializationUtils.cs
with Apache License 2.0
from census-instrumentation

private static void EncodeTag(ITag tag, MemoryStream byteArrayDataOutput)
        {
            byteArrayDataOutput.WriteByte(TagFieldId);
            EncodeString(tag.Key.Name, byteArrayDataOutput);
            EncodeString(tag.Value.replacedtring, byteArrayDataOutput);
        }

19 Source : TagContextDeserializationTest.cs
with Apache License 2.0
from census-instrumentation

[Fact]
        public void TestDeserializeTooLargeByteArrayThrowException()
        {
            MemoryStream output = new MemoryStream();
            output.WriteByte(SerializationUtils.VersionId);
            for (int i = 0; i < SerializationUtils.TagContextSerializedSizeLimit / 8 - 1; i++) {
                // Each tag will be with format {key : "0123", value : "0123"}, so the length of it is 8.
                String str;
                if (i < 10)
                {
                    str = "000" + i;
                }
                else if (i < 100)
                {
                    str = "00" + i;
                }
                else if (i < 1000)
                {
                    str = "0" + i;
                }
                else
                {
                    str = i.ToString();
                }
                EncodeTagToOutPut(str, str, output);
            }
            // The last tag will be of size 9, so the total size of the TagContext (8193) will be one byte
            // more than limit.
            EncodeTagToOutPut("last", "last1", output);

            byte[] bytes = output.ToArray();

            replacedert.Throws<TagContextDeserializationException>(() => serializer.FromByteArray(bytes));
        }

19 Source : TagContextDeserializationTest.cs
with Apache License 2.0
from census-instrumentation

[Fact]
        public void TestDeserializeTooLargeByteArrayThrowException_WithDuplicateTagKeys()
        {
            MemoryStream output = new MemoryStream();
            output.WriteByte(SerializationUtils.VersionId);
            for (int i = 0; i < SerializationUtils.TagContextSerializedSizeLimit / 8 - 1; i++) {
                // Each tag will be with format {key : "key_", value : "0123"}, so the length of it is 8.
                String str;
                if (i < 10)
                {
                    str = "000" + i;
                }
                else if (i < 100)
                {
                    str = "00" + i;
                }
                else if (i < 1000)
                {
                    str = "0" + i;
                }
                else
                {
                    str = i.ToString();
                }
                EncodeTagToOutPut("key_", str, output);
            }
            // The last tag will be of size 9, so the total size of the TagContext (8193) will be one byte
            // more than limit.
            EncodeTagToOutPut("key_", "last1", output);

            byte[] bytes = output.ToArray();

            replacedert.Throws<TagContextDeserializationException>(() => serializer.FromByteArray(bytes));
        }

19 Source : TagContextDeserializationTest.cs
with Apache License 2.0
from census-instrumentation

[Fact]
        public void TestDeserializeInvalidTagKey()
        {
            MemoryStream output = new MemoryStream();
            output.WriteByte(SerializationUtils.VersionId);

            // Encode an invalid tag key and a valid tag value:
            EncodeTagToOutPut("\u0002key", "value", output);
            byte[] bytes = output.ToArray();


            replacedert.Throws<TagContextDeserializationException>(() => serializer.FromByteArray(bytes));
        }

19 Source : TagContextDeserializationTest.cs
with Apache License 2.0
from census-instrumentation

[Fact]
        public void TestDeserializeInvalidTagValue()
        {
            MemoryStream output = new MemoryStream();
            output.WriteByte(SerializationUtils.VersionId);

            // Encode a valid tag key and an invalid tag value:
            EncodeTagToOutPut("my key", "val\u0003", output);
            byte[] bytes = output.ToArray();


            replacedert.Throws<TagContextDeserializationException>(() => serializer.FromByteArray(bytes));
        }

19 Source : TagContextDeserializationTest.cs
with Apache License 2.0
from census-instrumentation

[Fact]
        public void TestDeserializeOneTag()
        {
            MemoryStream output = new MemoryStream();
            output.WriteByte(SerializationUtils.VersionId);
            EncodeTagToOutPut("Key", "Value", output);
            ITagContext expected = tagger.EmptyBuilder.Put(TagKey.Create("Key"), TagValue.Create("Value")).Build();
            replacedert.Equal(expected, serializer.FromByteArray(output.ToArray()));
        }

19 Source : TagContextDeserializationTest.cs
with Apache License 2.0
from census-instrumentation

[Fact]
        public void TestDeserializeMultipleTags()
        {
            MemoryStream output = new MemoryStream();
            output.WriteByte(SerializationUtils.VersionId);
            EncodeTagToOutPut("Key1", "Value1", output);
            EncodeTagToOutPut("Key2", "Value2", output);
            ITagContext expected =
                    tagger
                    .EmptyBuilder
                    .Put(TagKey.Create("Key1"), TagValue.Create("Value1"))
                    .Put(TagKey.Create("Key2"), TagValue.Create("Value2"))
                    .Build();
            replacedert.Equal(expected, serializer.FromByteArray(output.ToArray()));
        }

19 Source : TagContextDeserializationTest.cs
with Apache License 2.0
from census-instrumentation

[Fact]
        public void TestDeserializeDuplicateKeys()
        {
            MemoryStream output = new MemoryStream();
            output.WriteByte(SerializationUtils.VersionId);
            EncodeTagToOutPut("Key1", "Value1", output);
            EncodeTagToOutPut("Key1", "Value2", output);
            ITagContext expected =
                tagger.EmptyBuilder.Put(TagKey.Create("Key1"), TagValue.Create("Value2")).Build();

            replacedert.Equal(expected, serializer.FromByteArray(output.ToArray()));
        }

19 Source : TagContextDeserializationTest.cs
with Apache License 2.0
from census-instrumentation

[Fact]
        public void TestDeserializeNonConsecutiveDuplicateKeys()
        {
            MemoryStream output = new MemoryStream();
            output.WriteByte(SerializationUtils.VersionId);
            EncodeTagToOutPut("Key1", "Value1", output);
            EncodeTagToOutPut("Key2", "Value2", output);
            EncodeTagToOutPut("Key3", "Value3", output);
            EncodeTagToOutPut("Key1", "Value4", output);
            EncodeTagToOutPut("Key2", "Value5", output);
            ITagContext expected =
                tagger
                    .EmptyBuilder
                    .Put(TagKey.Create("Key1"), TagValue.Create("Value4"))
                    .Put(TagKey.Create("Key2"), TagValue.Create("Value5"))
                    .Put(TagKey.Create("Key3"), TagValue.Create("Value3"))
                    .Build();
            replacedert.Equal(expected, serializer.FromByteArray(output.ToArray()));
        }

19 Source : TagContextDeserializationTest.cs
with Apache License 2.0
from census-instrumentation

[Fact]
        public void TestDeserializeDuplicateTags()
        {
            MemoryStream output = new MemoryStream();
            output.WriteByte(SerializationUtils.VersionId);
            EncodeTagToOutPut("Key1", "Value1", output);
            EncodeTagToOutPut("Key1", "Value1", output);
            ITagContext expected =
                tagger.EmptyBuilder.Put(TagKey.Create("Key1"), TagValue.Create("Value1")).Build();
            replacedert.Equal(expected, serializer.FromByteArray(output.ToArray()));
        }

19 Source : TagContextDeserializationTest.cs
with Apache License 2.0
from census-instrumentation

[Fact]
        public void TestDeserializeNonConsecutiveDuplicateTags()
        {
            MemoryStream output = new MemoryStream();
            output.WriteByte(SerializationUtils.VersionId);
            EncodeTagToOutPut("Key1", "Value1", output);
            EncodeTagToOutPut("Key2", "Value2", output);
            EncodeTagToOutPut("Key3", "Value3", output);
            EncodeTagToOutPut("Key1", "Value1", output);
            EncodeTagToOutPut("Key2", "Value2", output);
            ITagContext expected =
                tagger
                    .EmptyBuilder
                    .Put(TagKey.Create("Key1"), TagValue.Create("Value1"))
                    .Put(TagKey.Create("Key2"), TagValue.Create("Value2"))
                    .Put(TagKey.Create("Key3"), TagValue.Create("Value3"))
                    .Build();
            replacedert.Equal(expected, serializer.FromByteArray(output.ToArray()));
        }

19 Source : TagContextDeserializationTest.cs
with Apache License 2.0
from census-instrumentation

[Fact]
        public void StopParsingAtUnknownField()
        {
            MemoryStream output = new MemoryStream();
            output.WriteByte(SerializationUtils.VersionId);
            EncodeTagToOutPut("Key1", "Value1", output);
            EncodeTagToOutPut("Key2", "Value2", output);

            // Write unknown field ID 1.
            output.WriteByte(1);
            output.Write(new byte[] { 1, 2, 3, 4 }, 0, 4);

            EncodeTagToOutPut("Key3", "Value3", output);

            // key 3 should not be included
            ITagContext expected =
                tagger
                    .EmptyBuilder
                    .Put(TagKey.Create("Key1"), TagValue.Create("Value1"))
                    .Put(TagKey.Create("Key2"), TagValue.Create("Value2"))
                    .Build();
            replacedert.Equal(expected, serializer.FromByteArray(output.ToArray()));
        }

19 Source : TagContextDeserializationTest.cs
with Apache License 2.0
from census-instrumentation

[Fact]
        public void StopParsingAtUnknownField()
        {
            MemoryStream output = new MemoryStream();
            output.WriteByte(SerializationUtils.VersionId);
            EncodeTagToOutPut("Key1", "Value1", output);
            EncodeTagToOutPut("Key2", "Value2", output);

            // Write unknown field ID 1.
            output.WriteByte(1);
            output.Write(new byte[] { 1, 2, 3, 4 }, 0, 4);

            EncodeTagToOutPut("Key3", "Value3", output);

            // key 3 should not be included
            ITagContext expected =
                tagger
                    .EmptyBuilder
                    .Put(TagKey.Create("Key1"), TagValue.Create("Value1"))
                    .Put(TagKey.Create("Key2"), TagValue.Create("Value2"))
                    .Build();
            replacedert.Equal(expected, serializer.FromByteArray(output.ToArray()));
        }

19 Source : TagContextDeserializationTest.cs
with Apache License 2.0
from census-instrumentation

[Fact]
        public void StopParsingAtUnknownTagAtStart()
        {
            MemoryStream output = new MemoryStream();
            output.WriteByte(SerializationUtils.VersionId);

            // Write unknown field ID 1.
            output.WriteByte(1);
            output.Write(new byte[] { 1, 2, 3, 4 }, 0, 4);

            EncodeTagToOutPut("Key", "Value", output);
            replacedert.Equal(tagger.Empty, serializer.FromByteArray(output.ToArray()));
        }

19 Source : TagContextDeserializationTest.cs
with Apache License 2.0
from census-instrumentation

[Fact]
        public void StopParsingAtUnknownTagAtStart()
        {
            MemoryStream output = new MemoryStream();
            output.WriteByte(SerializationUtils.VersionId);

            // Write unknown field ID 1.
            output.WriteByte(1);
            output.Write(new byte[] { 1, 2, 3, 4 }, 0, 4);

            EncodeTagToOutPut("Key", "Value", output);
            replacedert.Equal(tagger.Empty, serializer.FromByteArray(output.ToArray()));
        }

19 Source : TagContextDeserializationTest.cs
with Apache License 2.0
from census-instrumentation

private static void EncodeTagToOutPut(String key, String value, MemoryStream output)
        {
            output.WriteByte(SerializationUtils.TagFieldId);
            EncodeString(key, output);
            EncodeString(value, output);
        }

19 Source : TagContextSerializationTest.cs
with Apache License 2.0
from census-instrumentation

private void TestSerialize(params ITag[] tags)
        {
            ITagContextBuilder builder = tagger.EmptyBuilder;
            foreach (var tag in tags)
            {
                builder.Put(tag.Key, tag.Value);
            }

            byte[] actual = serializer.ToByteArray(builder.Build());
            var tagsList = tags.ToList();
            var tagPermutation = Permutate(tagsList, tagsList.Count);
            ISet<String> possibleOutPuts = new HashSet<String>();
            foreach (List<ITag> list in tagPermutation) {
                MemoryStream expected = new MemoryStream();
                expected.WriteByte(SerializationUtils.VersionId);
                foreach (ITag tag in list) {
                    expected.WriteByte(SerializationUtils.TagFieldId);
                    EncodeString(tag.Key.Name, expected);
                    EncodeString(tag.Value.replacedtring, expected);
                }
                var bytes = expected.ToArray();
                possibleOutPuts.Add(Encoding.UTF8.GetString(bytes));
            }
            var exp = Encoding.UTF8.GetString(actual);
            replacedert.Contains(exp, possibleOutPuts);
        }

19 Source : HttpsClient.cs
with MIT License
from Cerbersec

private string readLine(SslStream sslStream)
        {
            using (var ms = new MemoryStream())
            {
                while (true)
                {
                    byte chr = (byte)sslStream.ReadByte();
                    if (chr == 13) // \r
                    {
                        sslStream.ReadByte(); // \n
                        break;
                    }
                    ms.WriteByte(chr);
                }
                return Encoding.UTF8.GetString(ms.ToArray());
            }
        }

19 Source : SchemaRegistrySerializerBuilder.cs
with MIT License
from ch-robinson

protected virtual ISerializer<T> Build<T>(
            int id,
            string json,
            TombstoneBehavior tombstoneBehavior
        ) {
            var schema = SchemaReader.Read(json);

            if (tombstoneBehavior != TombstoneBehavior.None)
            {
                if (default(T) != null)
                {
                    throw new UnsupportedTypeException(typeof(T), $"{typeof(T)} cannot represent tombstone values.");
                }

                var hasNull = schema is Abstract.NullSchema
                    || (schema is Abstract.UnionSchema union && union.Schemas.Any(s => s is Abstract.NullSchema));

                if (tombstoneBehavior == TombstoneBehavior.Strict && hasNull)
                {
                    throw new UnsupportedSchemaException(schema, "Tombstone serialization is not supported for schemas that can represent null values.");
                }
            }

            var bytes = BitConverter.GetBytes(id);

            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(bytes);
            }

            var serialize = SerializerBuilder.BuildDelegate<T>(schema);

            return new DelegateSerializer<T>((data, context) =>
            {
                if (data == null && tombstoneBehavior != TombstoneBehavior.None)
                {
                    if (context.Component == MessageComponentType.Value || tombstoneBehavior != TombstoneBehavior.Strict)
                    {
                        return null;
                    }
                }

                var stream = new MemoryStream();

                using (stream)
                {
                    stream.WriteByte(0x00);
                    stream.Write(bytes, 0, bytes.Length);

                    serialize(data, stream);
                }

                return stream.ToArray();
            });
        }

19 Source : AsyncSchemaRegistrySerializer.cs
with MIT License
from ch-robinson

protected virtual Func<T, byte[]> Build(int id, Abstract.Schema schema)
        {
            var bytes = BitConverter.GetBytes(id);

            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(bytes);
            }

            var serialize = SerializerBuilder.BuildDelegate<T>(schema);

            return value =>
            {
                var stream = new MemoryStream();

                using (stream)
                {
                    stream.WriteByte(0x00);
                    stream.Write(bytes, 0, bytes.Length);

                    serialize(value, stream);
                }

                return stream.ToArray();
            };
        }

19 Source : SrtpCipherCTR.cs
with MIT License
from chatop2020

public void Process(IBlockCipher cipher, MemoryStream data, int off, int len, byte[] iv)
        {
            // if data fits in inner buffer - use it. Otherwise allocate bigger
            // buffer store it to use it for later processing - up to a defined
            // maximum size.
            byte[] cipherStream = null;
            if (len > streamBuf.Length)
            {
                cipherStream = new byte[len];
                if (cipherStream.Length <= MAX_BUFFER_LENGTH)
                {
                    streamBuf = cipherStream;
                }
            }
            else
            {
                cipherStream = streamBuf;
            }

            GetCipherStream(cipher, cipherStream, len, iv);
            for (int i = 0; i < len; i++)
            {
                data.Position = i + off;
                var byteToWrite = data.ReadByte();
                data.Position = i + off;
                data.WriteByte((byte)(byteToWrite ^ cipherStream[i]));
            }
        }

19 Source : SrtpCipherF8.cs
with MIT License
from chatop2020

public static void ProcessBlock(IBlockCipher cipher, F8Context f8ctx,
                MemoryStream _in, int inOff, MemoryStream _out, int outOff, int len)
        {
            /*
             * XOR the previous key stream with IV'
             * ( S(-1) xor IV' )
             */
            for (int i = 0; i < BLKLEN; i++)
            {
                f8ctx.S[i] ^= f8ctx.ivAccent[i];
            }

            /*
             * Now XOR (S(n-1) xor IV') with the current counter, then increment 
             * the counter
             */
            f8ctx.S[12] ^= (byte)(f8ctx.J >> 24);
            f8ctx.S[13] ^= (byte)(f8ctx.J >> 16);
            f8ctx.S[14] ^= (byte)(f8ctx.J >> 8);
            f8ctx.S[15] ^= (byte)(f8ctx.J);
            f8ctx.J++;

            /*
             * Now compute the new key stream using AES encrypt
             */
            cipher.ProcessBlock(f8ctx.S, 0, f8ctx.S, 0);

            /*
             * As the last step XOR the plain text with the key stream to produce
             * the cipher text.
             */
            for (int i = 0; i < len; i++)
            {
                _in.Position = inOff + i;
                var inByte = _in.ReadByte();
                _out.Position = outOff + i;
                _out.WriteByte((byte)(inByte ^ f8ctx.S[i]));
            }
        }

19 Source : Mjpeg.cs
with MIT License
from chatop2020

public static byte[] ProcessMjpegFrame(List<RTPPacket> framePackets)
        {
            uint TypeSpecific, FragmentOffset, Type, type, Quality, Width, Height;
            ushort RestartInterval = 0, RestartCount = 0;
            //A byte which is bit mapped
            byte PrecisionTable = 0;
            ArraySegment<byte> tables = default;

            //Using a new MemoryStream for a Buffer
            using (System.IO.MemoryStream Buffer = new System.IO.MemoryStream())
            {
                //Loop each packet
                foreach (RTPPacket packet in framePackets.OrderBy(x => x.Header.SequenceNumber))
                {
                    //Payload starts at offset 0
                    int offset = 0;

                    //Handle Extension Headers
                    //if (packet.Extensions)
                    //{
                    //    This could be OnVif extension etc
                    //    http://www.onvif.org/specs/stream/ONVIF-Streaming-Spec-v220.pdf
                    //    Decode
                    //    packet.ExtensionBytes;
                    //    In a Derived Implementation
                    //}

                    //Decode RtpJpeg Header

                    TypeSpecific = (uint)(packet.Payload[offset++]);
                    FragmentOffset = (uint)(packet.Payload[offset++] << 16 | packet.Payload[offset++] << 8 | packet.Payload[offset++]);

                    #region RFC2435 -  The Type Field

                    /*
                     4.1.  The Type Field

          The Type field defines the abbreviated table-specification and
          additional JFIF-style parameters not defined by JPEG, since they are
          not present in the body of the transmitted JPEG data.

          Three ranges of the type field are currently defined. Types 0-63 are
          reserved as fixed, well-known mappings to be defined by this doreplacedent
          and future revisions of this doreplacedent. Types 64-127 are the same as
          types 0-63, except that restart markers are present in the JPEG data
          and a Restart Marker header appears immediately following the main
          JPEG header. Types 128-255 are free to be dynamically defined by a
          session setup protocol (which is beyond the scope of this doreplacedent).

          Of the first group of fixed mappings, types 0 and 1 are currently
          defined, along with the corresponding types 64 and 65 that indicate
          the presence of restart markers.  They correspond to an abbreviated
          table-specification indicating the "Baseline DCT sequential" mode,
          8-bit samples, square pixels, three components in the YUV color
          space, standard Huffman tables as defined in [1, Annex K.3], and a
          single interleaved scan with a scan component selector indicating
          components 1, 2, and 3 in that order.  The Y, U, and V color planes
          correspond to component numbers 1, 2, and 3, respectively.  Component
          1 (i.e., the luminance plane) uses Huffman table number 0 and
          quantization table number 0 (defined below) and components 2 and 3
          (i.e., the chrominance planes) use Huffman table number 1 and
          quantization table number 1 (defined below).

          Type numbers 2-5 are reserved and SHOULD NOT be used.  Applications
          based on previous versions of this doreplacedent (RFC 2035) should be
          updated to indicate the presence of restart markers with type 64 or
          65 and the Restart Marker header.

          The two RTP/JPEG types currently defined are described below:

                            horizontal   vertical   Quantization
           types  component samp. fact. samp. fact. table number
          +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
          |       |  1 (Y)  |     2     |     1     |     0     |
          | 0, 64 |  2 (U)  |     1     |     1     |     1     |
          |       |  3 (V)  |     1     |     1     |     1     |
          +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
          |       |  1 (Y)  |     2     |     2     |     0     |
          | 1, 65 |  2 (U)  |     1     |     1     |     1     |
          |       |  3 (V)  |     1     |     1     |     1     |
          +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

          These sampling factors indicate that the chrominance components of
          type 0 video is downsampled horizontally by 2 (often called 4:2:2)
          while the chrominance components of type 1 video are downsampled both
          horizontally and vertically by 2 (often called 4:2:0).

          Types 0 and 1 can be used to carry both progressively scanned and
          interlaced image data.  This is encoded using the Type-specific field
          in the main JPEG header.  The following values are defined:

          0 : Image is progressively scanned.  On a computer monitor, it can
          be displayed as-is at the specified width and height.

          1 : Image is an odd field of an interlaced video signal.  The
          height specified in the main JPEG header is half of the height
          of the entire displayed image.  This field should be de-
          interlaced with the even field following it such that lines
          from each of the images alternate.  Corresponding lines from
          the even field should appear just above those same lines from
          the odd field.

          2 : Image is an even field of an interlaced video signal.

          3 : Image is a single field from an interlaced video signal, but
          it should be displayed full frame as if it were received as
          both the odd & even fields of the frame.  On a computer
          monitor, each line in the image should be displayed twice,
          doubling the height of the image.
                     */

                    #endregion

                    Type = (uint)(packet.Payload[offset++]);
                    type = Type & 1;
                    if (type > 3 || type > 6)
                    {
                        throw new ArgumentException("Type numbers 2-5 are reserved and SHOULD NOT be used.  Applications on RFC 2035 should be updated to indicate the presence of restart markers with type 64 or 65 and the Restart Marker header.");
                    }

                    Quality = (uint)packet.Payload[offset++];
                    Width = (uint)(packet.Payload[offset++] * 8); // This should have been 128 or > and the standard would have worked for all resolutions
                    Height = (uint)(packet.Payload[offset++] * 8);// Now in certain highres profiles you will need an OnVif extension before the RtpJpeg Header
                                                                  //It is worth noting Rtp does not care what you send and more tags such as comments and or higher resolution pictures may be sent and these values will simply be ignored.

                    if (Width == 0 || Height == 0)
                    {
                        logger.LogWarning("ProcessMjpegFrame could not determine either the width or height of the jpeg frame (width={0}, height={1}).", Width, Height);
                    }

                    //Restart Interval 64 - 127
                    if (Type > 63 && Type < 128)
                    {
                        /*
                           This header MUST be present immediately after the main JPEG header
                           when using types 64-127.  It provides the additional information
                           required to properly decode a data stream containing restart markers.

                            0                   1                   2                   3
                            0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
                           +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
                           |       Restart Interval        |F|L|       Restart Count       |
                           +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
                         */
                        RestartInterval = (ushort)(packet.Payload[offset++] << 8 | packet.Payload[offset++]);
                        RestartCount = (ushort)((packet.Payload[offset++] << 8 | packet.Payload[offset++]) & 0x3fff);
                    }

                    //QTables Only occur in the first packet
                    if (FragmentOffset == 0)
                    {
                        //If the quality > 127 there are usually Quantization Tables
                        if (Quality > 127)
                        {
                            if ((packet.Payload[offset++]) != 0)
                            {
                                //Must Be Zero is Not Zero
                                if (System.Diagnostics.Debugger.IsAttached)
                                {
                                    System.Diagnostics.Debugger.Break();
                                }
                            }

                            //Precision
                            PrecisionTable = (packet.Payload[offset++]);

                            #region RFC2435 Length Field

                            /*

              The Length field is set to the length in bytes of the quantization
              table data to follow.  The Length field MAY be set to zero to
              indicate that no quantization table data is included in this frame.
              See section 4.2 for more information.  If the Length field in a
              received packet is larger than the remaining number of bytes, the
              packet MUST be discarded.

              When table data is included, the number of tables present depends on
              the JPEG type field.  For example, type 0 uses two tables (one for
              the luminance component and one shared by the chrominance
              components).  Each table is an array of 64 values given in zig-zag
              order, identical to the format used in a JFIF DQT marker segment.

              For each quantization table present, a bit in the Precision field
              specifies the size of the coefficients in that table.  If the bit is
              zero, the coefficients are 8 bits yielding a table length of 64
              bytes.  If the bit is one, the coefficients are 16 bits for a table
              length of 128 bytes.  For 16 bit tables, the coefficients are
              presented in network byte order.  The rightmost bit in the Precision
              field (bit 15 in the diagram above) corresponds to the first table
              and each additional table uses the next bit to the left.  Bits beyond
              those corresponding to the tables needed by the type in use MUST be
              ignored.

                                 */

                            #endregion

                            //Length of all tables
                            ushort Length = (ushort)(packet.Payload[offset++] << 8 | packet.Payload[offset++]);

                            //If there is Table Data Read it
                            if (Length > 0)
                            {
                                tables = new ArraySegment<byte>(packet.Payload, offset, (int)Length);
                                offset += (int)Length;
                            }
                            else if (Length > packet.Payload.Length - offset)
                            {
                                continue; // The packet must be discarded
                            }
                            else // Create it from the Quality
                            {
                                tables = new ArraySegment<byte>(CreateQuantizationTables(Quality, type, PrecisionTable));
                            }
                        }
                        else // Create from the Quality
                        {
                            tables = new ArraySegment<byte>(CreateQuantizationTables(type, Quality, PrecisionTable));
                        }

                        byte[] header = CreateJFIFHeader(type, Width, Height, tables, PrecisionTable, RestartInterval);
                        Buffer.Write(header, 0, header.Length);
                    }

                    //Write the Payload data from the offset
                    Buffer.Write(packet.Payload, offset, packet.Payload.Length - offset);
                }

                //Check for EOI Marker
                Buffer.Seek(-1, System.IO.SeekOrigin.Current);

                if (Buffer.ReadByte() != Tags.EndOfInformation)
                {
                    Buffer.WriteByte(Tags.Prefix);
                    Buffer.WriteByte(Tags.EndOfInformation);
                }

                //Go back to the beginning
                Buffer.Position = 0;

                //This article explains in detail what exactly happens: http://support.microsoft.com/kb/814675
                //In short, for a lifetime of an Image constructed from a stream, the stream must not be destroyed.
                //Image = new System.Drawing.Bitmap(System.Drawing.Image.FromStream(Buffer, true, true));
                //DO NOT USE THE EMBEDDED COLOR MANGEMENT
                //Image = System.Drawing.Image.FromStream(Buffer, false, true);

                return Buffer.ToArray();
            }
        }

19 Source : H264Depacketiser.cs
with MIT License
from chatop2020

public virtual MemoryStream ProcessRTPPayload(byte[] rtpPayload, ushort seqNum, uint timestamp, int markbit, out bool isKeyFrame)
        {
            List<byte[]> nal_units = ProcessRTPPayloadAsNals(rtpPayload, seqNum, timestamp, markbit, out isKeyFrame);

            if (nal_units != null)
            {
                //Calculate total buffer size
                long totalBufferSize = 0;
                for (int i = 0; i < nal_units.Count; i++)
                {
                    var nal = nal_units[i];
                    long remaining = nal.Length;

                    if (remaining > 0)
                    {
                        totalBufferSize += remaining + 4; //nal + 0001
                    }
                    else
                    {
                        nal_units.RemoveAt(i);
                        i--;
                    }
                }

                //Merge nals in same buffer using Annex-B separator (0001)
                MemoryStream data = new MemoryStream(new byte[totalBufferSize]);
                foreach (var nal in nal_units)
                {
                    data.WriteByte(0);
                    data.WriteByte(0);
                    data.WriteByte(0);
                    data.WriteByte(1);
                    data.Write(nal, 0, nal.Length);
                }
                return data;
            }
            return null;
        }

19 Source : H264Depacketiser.cs
with MIT License
from chatop2020

protected virtual List<byte[]> ProcessH264PayloadFrame(List<KeyValuePair<int, byte[]>> rtp_payloads, out bool isKeyFrame)
        {
            bool? isKeyFrameNullable = null;
            List<byte[]> nal_units = new List<byte[]>(); // Stores the NAL units for a Video Frame. May be more than one NAL unit in a video frame.

            for (int payload_index = 0; payload_index < rtp_payloads.Count; payload_index++)
            {
                // Examine the first rtp_payload and the first byte (the NAL header)
                int nal_header_f_bit = (rtp_payloads[payload_index].Value[0] >> 7) & 0x01;
                int nal_header_nri = (rtp_payloads[payload_index].Value[0] >> 5) & 0x03;
                int nal_header_type = (rtp_payloads[payload_index].Value[0] >> 0) & 0x1F;

                // If the Nal Header Type is in the range 1..23 this is a normal NAL (not fragmented)
                // So write the NAL to the file
                if (nal_header_type >= 1 && nal_header_type <= 23)
                {
                    norm++;
                    //Check if is Key Frame
                    CheckKeyFrame(nal_header_type, ref isKeyFrameNullable);

                    nal_units.Add(rtp_payloads[payload_index].Value);
                }
                // There are 4 types of Aggregation Packet (split over RTP payloads)
                else if (nal_header_type == 24)
                {
                    stap_a++;

                    // RTP packet contains multiple NALs, each with a 16 bit header
                    //   Read 16 byte size
                    //   Read NAL
                    try
                    {
                        int ptr = 1; // start after the nal_header_type which was '24'
                        // if we have at least 2 more bytes (the 16 bit size) then consume more data
                        while (ptr + 2 < (rtp_payloads[payload_index].Value.Length - 1))
                        {
                            int size = (rtp_payloads[payload_index].Value[ptr] << 8) + (rtp_payloads[payload_index].Value[ptr + 1] << 0);
                            ptr = ptr + 2;
                            byte[] nal = new byte[size];
                            Buffer.BlockCopy(rtp_payloads[payload_index].Value, ptr, nal, 0, size); // copy the NAL

                            byte reconstructed_nal_type = (byte)((nal[0] >> 0) & 0x1F);
                            //Check if is Key Frame
                            CheckKeyFrame(reconstructed_nal_type, ref isKeyFrameNullable);

                            nal_units.Add(nal); // Add to list of NALs for this RTP frame. Start Codes like 00 00 00 01 get added later
                            ptr = ptr + size;
                        }
                    }
                    catch
                    {
                    }
                }
                else if (nal_header_type == 25)
                {
                    stap_b++;
                }
                else if (nal_header_type == 26)
                {
                    mtap16++;
                }
                else if (nal_header_type == 27)
                {
                    mtap24++;
                }
                else if (nal_header_type == 28)
                {
                    fu_a++;

                    // Parse Fragmentation Unit Header
                    int fu_indicator = rtp_payloads[payload_index].Value[0];
                    int fu_header_s = (rtp_payloads[payload_index].Value[1] >> 7) & 0x01;  // start marker
                    int fu_header_e = (rtp_payloads[payload_index].Value[1] >> 6) & 0x01;  // end marker
                    int fu_header_r = (rtp_payloads[payload_index].Value[1] >> 5) & 0x01;  // reserved. should be 0
                    int fu_header_type = (rtp_payloads[payload_index].Value[1] >> 0) & 0x1F; // Original NAL unit header

                    // Check Start and End flags
                    if (fu_header_s == 1 && fu_header_e == 0)
                    {
                        // Start of Fragment.
                        // Initialise the fragmented_nal byte array
                        // Build the NAL header with the original F and NRI flags but use the the Type field from the fu_header_type
                        byte reconstructed_nal_type = (byte)((nal_header_f_bit << 7) + (nal_header_nri << 5) + fu_header_type);

                        // Empty the stream
                        fragmented_nal.SetLength(0);

                        // Add reconstructed_nal_type byte to the memory stream
                        fragmented_nal.WriteByte((byte)reconstructed_nal_type);

                        // copy the rest of the RTP payload to the memory stream
                        fragmented_nal.Write(rtp_payloads[payload_index].Value, 2, rtp_payloads[payload_index].Value.Length - 2);
                    }

                    if (fu_header_s == 0 && fu_header_e == 0)
                    {
                        // Middle part of Fragment
                        // Append this payload to the fragmented_nal
                        // Data starts after the NAL Unit Type byte and the FU Header byte
                        fragmented_nal.Write(rtp_payloads[payload_index].Value, 2, rtp_payloads[payload_index].Value.Length - 2);
                    }

                    if (fu_header_s == 0 && fu_header_e == 1)
                    {
                        // End part of Fragment
                        // Append this payload to the fragmented_nal
                        // Data starts after the NAL Unit Type byte and the FU Header byte
                        fragmented_nal.Write(rtp_payloads[payload_index].Value, 2, rtp_payloads[payload_index].Value.Length - 2);

                        var fragmeted_nal_array = fragmented_nal.ToArray();
                        byte reconstructed_nal_type = (byte)((fragmeted_nal_array[0] >> 0) & 0x1F);

                        //Check if is Key Frame
                        CheckKeyFrame(reconstructed_nal_type, ref isKeyFrameNullable);

                        // Add the NAL to the array of NAL units
                        nal_units.Add(fragmeted_nal_array);
                        fragmented_nal.SetLength(0);
                    }
                }

                else if (nal_header_type == 29)
                {
                    fu_b++;
                }
            }

            isKeyFrame = isKeyFrameNullable != null ? isKeyFrameNullable.Value : false;

            // Output all the NALs that form one RTP Frame (one frame of video)
            return nal_units;
        }

19 Source : MemoryBuffer.cs
with MIT License
from chkr1011

public void Write(byte buffer)
        {
            _memoryStream.WriteByte(buffer);
        }

19 Source : StringExtensions.cs
with GNU General Public License v3.0
from CircuitLord

public static Byte[] UrlDecode(this String value)
        {
            var ms = new MemoryStream();

            for (var i = 0; i < value.Length; i++)
            {
                var chr = value[i];

                if (chr == Symbols.Plus)
                {
                    var b = (Byte)Symbols.Space;
                    ms.WriteByte(b);
                }
                else if (chr == Symbols.Percent)
                {
                    if (i + 2 >= value.Length)
                    {
                        throw new FormatException();
                    }

                    var code = 16 * value[++i].FromHex() + value[++i].FromHex();
                    var b = (Byte)code;
                    ms.WriteByte(b);
                }
                else
                {
                    var b = (Byte)chr;
                    ms.WriteByte(b);
                }
            }

            return ms.ToArray();
        }

19 Source : StateReader.cs
with MIT License
from CityOfZion

protected virtual bool Storage_Find(IExecutionEngine engine)
        {
            var storageContext = engine.CurrentContext.EvaluationStack.PopObject<StorageContext>();
            if (storageContext == null) return false;
            if (!CheckStorageContext(storageContext)) return false;

            var prefix = engine.CurrentContext.EvaluationStack.PopByteArray();
            byte[] prefixKey;

            using (var ms = new MemoryStream())
            {
                var index = 0;
                var remain = prefix.Length;

                while (remain >= 16)
                {
                    ms.Write(prefix, index, 16);
                    ms.WriteByte(0);
                    index += 16;
                    remain -= 16;
                }

                if (remain > 0)
                    ms.Write(prefix, index, remain);

                prefixKey = storageContext.ScriptHash.ToArray().Concat(ms.ToArray()).ToArray();
            }

            // TODO: Find a better way not to expose engine.CurrentContext.EvaluationStackItem types or Create* methods
            var enumerator = Storages.Find(prefixKey)
                .Where(p => p.Key.Key.Take(prefix.Length).SequenceEqual(prefix))
                .Select(p => new KeyValuePair<StackItemBase, StackItemBase>(engine.CurrentContext.EvaluationStack.CreateByteArray(p.Key.Key), engine.CurrentContext.EvaluationStack.CreateByteArray(p.Value.Value)))
                .GetEnumerator();
            var keyEnumerator = new KeyEnumerator(enumerator);

            engine.CurrentContext.EvaluationStack.PushObject(keyEnumerator);
            _disposables.Add(keyEnumerator);

            return true;
        }

19 Source : ScriptBuilder.cs
with MIT License
from CityOfZion

public ScriptBuilder Emit(params EVMOpCode[] ops)
        {
            foreach (EVMOpCode op in ops)
                _writer.WriteByte((byte)op);

            return this;
        }

19 Source : ScriptBuilder.cs
with MIT License
from CityOfZion

public virtual ScriptBuilder EmitPush(byte[] data)
        {
            if (data == null) throw new ArgumentNullException();

            if (data.Length <= (int)EVMOpCode.PUSHBYTES75)
            {
                _writer.WriteByte((byte)data.Length);
                _writer.Write(data, 0, data.Length);
            }
            else if (data.Length < 0x100)
            {
                Emit(EVMOpCode.PUSHDATA1);
                _writer.WriteByte((byte)data.Length);
                _writer.Write(data, 0, data.Length);
            }
            else if (data.Length < 0x10000)
            {
                Emit(EVMOpCode.PUSHDATA2);
                _writer.Write(((ushort)data.Length).GetBytes(), 0, 2);
                _writer.Write(data, 0, data.Length);
            }
            else// if (data.Length < 0x100000000L)
            {
                Emit(EVMOpCode.PUSHDATA4);
                _writer.Write(data.Length.GetBytes(), 0, 4);
                _writer.Write(data, 0, data.Length);
            }
            return this;
        }

See More Examples