Esempio n. 1
0
        public T Read(IDataReader reader)
        {
            int length = reader.ReadInt32();

            byte[] byteArr = new byte[length];
            reader.Read(ref byteArr, 0, length);
            return(_codec.Decode(byteArr));
        }
Esempio n. 2
0
        /// <summary>
        /// Reads the value from the link synchronously
        /// </summary>
        public T Read()
        {
            if (_disposed)
            {
                Exceptions.Throw(new IllegalStateException("Link has been disposed."), LOGGER);
            }

            byte[] message = _channel.Read();
            return((message == null) ? default(T) : _codec.Decode(message));
        }
Esempio n. 3
0
        /// <summary>
        ///    Loads an image from a stream.
        /// </summary>
        /// <remarks>
        ///    This method allows loading an image from a stream, which is helpful for when
        ///    images are being decompressed from an archive into a stream, which needs to be
        ///    loaded as is.
        /// </remarks>
        /// <param name="stream">Stream serving as the data source.</param>
        /// <param name="type">
        ///    Type (i.e. file format) of image.  Used to decide which image decompression codec to use.
        /// </param>
        public static Image FromStream(Stream stream, string type)
        {
            // find the codec for this file type
            ICodec codec = CodecManager.Instance.GetCodec(type);

            MemoryStream decoded = new MemoryStream();

            ImageCodec.ImageData data = (ImageCodec.ImageData)codec.Decode(stream, decoded);

            Image image = new Image();

            // copy the image data
            image.height     = data.height;
            image.width      = data.width;
            image.depth      = data.depth;
            image.format     = data.format;
            image.flags      = data.flags;
            image.numMipMaps = data.numMipMaps;

            // stuff the image data into an array
            byte[] buffer = new byte[decoded.Length];
            decoded.Position = 0;
            decoded.Read(buffer, 0, buffer.Length);
            decoded.Close();

            image.SetBuffer(buffer);

            return(image);
        }
Esempio n. 4
0
        public Channel(ICodec <TPacket> codec, Stream inputStream, Stream outputStream)
        {
            Codec        = codec;
            BufferStream = new BufferedStream(outputStream);

            Writer = new BinaryWriter(BufferStream);
            Reader = new BinaryReader(inputStream);
            _cancellationTokenSource = new CancellationTokenSource();
            var cancellationToken = _cancellationTokenSource.Token;

            _receptionTask = Task.Factory.StartNew(async() =>
            {
                while (!cancellationToken.IsCancellationRequested)
                {
                    try
                    {
                        var packet = codec.Decode(Reader);
                        OnDataReceived(new DataReceivedEventArg <TPacket>(packet));
                    }
                    catch (OperationCanceledException)
                    {
                        break;
                    }
                    catch (Exception ex)
                    {
                        OnErrorReceived(ex);
                        await Task.Delay(100);
                    }
                }
            });
        }
        // Token: 0x06004CA7 RID: 19623 RVA: 0x0019B4BC File Offset: 0x001998BC
        public static float[] DecompressAudio(byte[] data, int samples, int channels, bool threeD, BandMode mode, ICodec Codec, float gain)
        {
            int frequency = 4000;

            if (mode == BandMode.Narrow)
            {
                frequency = 8000;
            }
            else if (mode == BandMode.Wide)
            {
                frequency = 16000;
            }
            else if (mode == BandMode.UltraWide)
            {
                frequency = 32000;
            }
            else if (mode == BandMode.Opus48k)
            {
                frequency = 48000;
            }
            short[] array  = Codec.Decode(data, mode);
            float[] result = USpeakAudioClipConverter.ShortsToAudioData(array, channels, frequency, threeD, gain);
            USpeakPoolUtils.Return(array);
            return(result);
        }
Esempio n. 6
0
//		public static AudioClip DecompressAudioClip( byte[] data, int samples, int channels, bool threeD, BandMode mode, float gain )
        public static AudioClip DecompressAudioClip(byte[] data, int samples, int channels, bool threeD, float gain)
        {
            int frequency = 4000;

//			if( mode == BandMode.Narrow )
//			{
//				frequency = 8000;
//			}
//			else if( mode == BandMode.Wide )
//			{
//				frequency = 16000;
//			}

            byte[] d;
            d = unzip(data);

            short[] pcm = Codec.Decode(d);

            tmp.Clear();
            tmp.AddRange(pcm);

            //while( tmp.Count > 1 && Mathf.Abs( tmp[ tmp.Count - 1 ] ) <= 10 )
            //{
            //    tmp.RemoveAt( tmp.Count - 1 );
            //}

            //while( tmp.Count > 1 && Mathf.Abs( tmp[ 0 ] ) <= 10 )
            //{
            //    tmp.RemoveAt( 0 );
            //}

            return(USpeakAudioClipConverter.ShortsToAudioClip(tmp.ToArray(), channels, frequency, threeD, gain));
        }
        /// <summary>
        /// Decompress the given encoded audio data
        /// </summary>
        /// <param name="data">The encoded audio</param>
        /// <param name="samples">The number of encoded samples</param>
        /// <param name="channels">The number of channels</param>
        /// <param name="threeD">Whether the audio is 3D</param>
        /// <param name="mode">The bandwidth mode used to encode the data</param>
        /// <param name="Codec">The codec to decode the data with</param>
        /// <param name="gain">The gain to apply to the decoded audio</param>
        /// <returns>32bit raw audio data</returns>
        public static float[] DecompressAudio(byte[] data, int samples, int channels, bool threeD, BandMode mode, ICodec Codec, float gain)
        {
            int frequency = 4000;

            if (mode == BandMode.Narrow)
            {
                frequency = 8000;
            }
            else if (mode == BandMode.Wide)
            {
                frequency = 16000;
            }

            byte[] d;
            //d = unzip( data );
            d = data;

            short[] pcm = Codec.Decode(d, mode);

            tmp.Clear();
            tmp.AddRange(pcm);

            USpeakPoolUtils.Return(pcm);

            return(USpeakAudioClipConverter.ShortsToAudioData(tmp.ToArray(), channels, frequency, threeD, gain));
        }
Esempio n. 8
0
 public static object Decode(this ICodec codec, TcpPacket packet)
 {
     if (packet == null)
     {
         throw new ArgumentNullException(nameof(packet));
     }
     return(codec.Decode(packet.Data));
 }
        public static FilterInvocation DecodeFilterInvoked(this CommandReply self, ICodec codec)
        {
            if (self.Type != ReplyType.FilterInvoked)
            {
                throw new Exception("this is not FilterInvoked reply");
            }

            return(codec.Decode <FilterInvocation>(self.ReplyData));
        }
        public static ServiceCall DecodeServiceCall(this CommandReply self, ICodec codec)
        {
            if (self.Type != ReplyType.ServiceInvoked)
            {
                throw new Exception("this is not ServiceInvoked reply");
            }

            return(codec.Decode <ServiceCall>(self.ReplyData));
        }
//      public static byte[] CompressAudioClip( AudioClip clip, out int samples, BandMode mode, float gain = 1.0f )
//      {
//          data.Clear();
//          samples = 0;
//          short[] b = USpeakAudioClipConverter.AudioClipToShorts( clip, gain );
//          byte[] mlaw = Codec.Encode( b, mode );
//          data.AddRange( mlaw );
//          return zip( data.ToArray() );
//      }

        public static AudioClip DecompressAudioClip(byte[] data, int samples, int channels, bool threeD, BandMode mode, float gain)
        {
//          byte[] d;
//          d = unzip( data );
            short[] pcm = Codec.Decode(data, mode);
            tmp.Clear();
            tmp.AddRange(pcm);
            return(USpeakAudioClipConverter.ShortsToAudioClip(tmp.ToArray(), channels, WSpeak.getFrequency(mode), threeD, gain));
        }
        /// <summary>returns null if timeout was reached</summary>
        public CommandReply ReadReplyOrNull(TimeSpan?timeout = null)
        {
            var rawReply = ReadLineOrNull(timeout);

            if (rawReply == null)
            {
                return(null);
            }
            return(_codec.Decode <CommandReply>(rawReply));
        }
Esempio n. 13
0
        public static object Decode(this ICodec codec, UdpPacket packet)
        {
            UdpData udpData = !(packet == null) ? packet.Payload as UdpData : throw new ArgumentNullException(nameof(packet));

            if (udpData == null)
            {
                throw new InvalidOperationException("No data");
            }
            return(codec.Decode(udpData.Data));
        }
Esempio n. 14
0
        /// <inheritdoc cref="Owasp.Esapi.Interfaces.IEncoder.Decode(string, string)" />
        public string Decode(string codecName, string input)
        {
            ICodec codec = GetCodec(codecName);

            if (codec == null)
            {
                throw new ArgumentOutOfRangeException("codecName");
            }

            return(codec.Decode(input));
        }
Esempio n. 15
0
        static Datamodel Load_Internal(Stream stream, DeferredMode defer_mode = DeferredMode.Automatic)
        {
            stream.Seek(0, SeekOrigin.Begin);
            var header = String.Empty;
            int b;

            while ((b = stream.ReadByte()) != -1)
            {
                header += (char)b;
                if (b == '>')
                {
                    break;
                }
                if (header.Length > 128) // probably not a DMX at this point
                {
                    break;
                }
            }

            var match = System.Text.RegularExpressions.Regex.Match(header, CodecUtilities.HeaderPattern_Regex);

            if (!match.Success || match.Groups.Count != 5)
            {
                throw new InvalidOperationException("Could not read file header.");
            }

            string encoding         = match.Groups[1].Value;
            int    encoding_version = int.Parse(match.Groups[2].Value);

            string format         = match.Groups[3].Value;
            int    format_version = int.Parse(match.Groups[4].Value);

            ICodec codec = GetCodec(encoding, encoding_version);

            var dm = codec.Decode(encoding_version, format, format_version, stream, defer_mode);

            if (defer_mode == DeferredMode.Automatic && codec is IDeferredAttributeCodec)
            {
                dm.Stream = stream;
                dm.Codec  = (IDeferredAttributeCodec)codec;
            }

            dm.Format        = format;
            dm.FormatVersion = format_version;

            dm.Encoding        = encoding;
            dm.EncodingVersion = encoding_version;

            return(dm);
        }
Esempio n. 16
0
        /// <summary>
        /// Deserialize the byte array into NsMessage.
        /// </summary>
        /// <param name="data">The serialized byte array</param>
        /// <returns>The deserialized NsMessage</returns>
        public NsMessage <T> Decode(byte[] data)
        {
            using (var stream = new MemoryStream(data))
            {
                NsMessageProto proto = Serializer.Deserialize <NsMessageProto>(stream);

                IIdentifier   sourceId = _idFactory.Create(proto.SourceId);
                IIdentifier   destId   = _idFactory.Create(proto.DestId);
                NsMessage <T> message  = new NsMessage <T>(sourceId, destId);

                var messages = proto.Data.Select(byteArr => _codec.Decode(byteArr));
                message.Data.AddRange(messages);
                return(message);
            }
        }
Esempio n. 17
0
        public int Read(byte *p, int length)
        {
            var read = 0;

            while (read < length)
            {
                // Read the next block from the underlying stream
                if (_decodedBuffer.Offset >= _decodedBuffer.End)
                {
                    _encodedBuffer.Reset();

                    // Read the payload length
                    if (_underlying.Read(_encodedBuffer.Data, 0, sizeOfHeader) != sizeOfHeader)
                    {
                        return(read); // Ends of stream
                    }
                    var payloadLength = ((PayloadHeader *)_encodedBuffer.Ptr)->PayloadLength;
                    if (_underlying.Read(_encodedBuffer.Data, 0, payloadLength + sizeof(byte)) != payloadLength + sizeof(byte))
                    {
                        return(read); // Ends of stream
                    }
                    // Decode data
                    _decodedBuffer.Reset();
                    _decodedBuffer.End += _codec.Decode(_encodedBuffer.Ptr, payloadLength, (T *)_decodedBuffer.Ptr) * sizeof(T);

                    // Checksum coherency
                    if (*(_encodedBuffer.Ptr + payloadLength) != CHECKSUM)
                    {
                        throw new CorruptedDataException("Checksum failed");
                    }
                }

                var bytesToRead = Math.Min(length - read, (int)(_decodedBuffer.End - _decodedBuffer.Offset));
                Unsafe.CopyBlock(p, _decodedBuffer.Offset, (uint)bytesToRead);
                read += bytesToRead;
                p    += bytesToRead;
                _decodedBuffer.Offset += bytesToRead;

#if Debug
                if ((int)(_blockEnd - _offset) <= remainingBytes)
                {
                    throw new InvalidOperationException($"The codec {typeof(TCodec)} decoded nothing and the read is fallen in an infinity loop");
                }
#endif
            }

            return(read);
        }
 public static float[] DecompressAudio(byte[] data, int samples, int channels, bool threeD, BandMode mode, ICodec Codec, float gain)
 {
     int num = 4000;
     if (mode == BandMode.Narrow)
     {
         num = 8000;
     }
     else if (mode == BandMode.Wide)
     {
         num = 16000;
     }
     short[] numArray = Codec.Decode(data, mode);
     USpeakAudioClipCompressor.tmp.Clear();
     USpeakAudioClipCompressor.tmp.AddRange(numArray);
     USpeakPoolUtils.Return(numArray);
     return USpeakAudioClipConverter.ShortsToAudioData(USpeakAudioClipCompressor.tmp.ToArray(), channels, num, threeD, gain);
 }
Esempio n. 19
0
        public void Test_Decode()
        {
            MockRepository mocks = new MockRepository();

            string testString = Guid.NewGuid().ToString();
            string codecName  = Guid.NewGuid().ToString();

            ICodec codec = mocks.StrictMock <ICodec>();

            Expect.Call(codec.Decode(testString)).Return(testString);
            mocks.ReplayAll();

            Esapi.Encoder.AddCodec(codecName, codec);
            Assert.ReferenceEquals(Esapi.Encoder.GetCodec(codecName), codec);

            Assert.AreEqual(testString, Esapi.Encoder.Decode(codecName, testString));
            mocks.VerifyAll();
        }
Esempio n. 20
0
        public static float[] DecompressAudio(byte[] data, int samples, int channels, bool threeD, BandMode mode, ICodec Codec, float gain)
        {
            int num = 4000;

            if (mode == BandMode.Narrow)
            {
                num = 8000;
            }
            else if (mode == BandMode.Wide)
            {
                num = 16000;
            }
            short[] numArray = Codec.Decode(data, mode);
            USpeakAudioClipCompressor.tmp.Clear();
            USpeakAudioClipCompressor.tmp.AddRange(numArray);
            USpeakPoolUtils.Return(numArray);
            return(USpeakAudioClipConverter.ShortsToAudioData(USpeakAudioClipCompressor.tmp.ToArray(), channels, num, threeD, gain));
        }
Esempio n. 21
0
        static void Import(DBTableControl.DBEditorTableControl _parentDbEdtiorTable, string filename, ICodec <DBFile> codec)
        {
            System.Windows.Forms.OpenFileDialog openDBFileDialog = new System.Windows.Forms.OpenFileDialog
            {
                InitialDirectory = _parentDbEdtiorTable._exportDirectory,
                FileName         = filename
            };

            bool tryAgain = false;

            if (openDBFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                _parentDbEdtiorTable._importDirectory = System.IO.Path.GetDirectoryName(openDBFileDialog.FileName);
                do
                {
                    try
                    {
                        try
                        {
                            using (var stream = new MemoryStream(File.ReadAllBytes(openDBFileDialog.FileName)))
                            {
                                var loadedfile = codec.Decode(stream);
                                // No need to import to editedFile directly, since it will be handled in the
                                _parentDbEdtiorTable.Import(loadedfile);
                            }
                        }
                        catch (DBFileNotSupportedException exception)
                        {
                            _parentDbEdtiorTable.showDBFileNotSupportedMessage(exception.Message);
                        }

                        _parentDbEdtiorTable.CurrentPackedFile.Data = (_parentDbEdtiorTable._codec.Encode(_parentDbEdtiorTable.EditedFile));
                    }
                    catch (Exception ex)
                    {
                        tryAgain = (System.Windows.Forms.MessageBox.Show(string.Format("Import failed: {0}", ex.Message),
                                                                         "Import failed",
                                                                         System.Windows.Forms.MessageBoxButtons.RetryCancel)
                                    == System.Windows.Forms.DialogResult.Retry);
                    }
                } while (tryAgain);
            }
        }
Esempio n. 22
0
        public static float[] DecompressAudio(byte[] data, int samples, int channels, bool threeD, BandMode mode, ICodec Codec, float gain)
        {
            int frequency = 0xfa0;

            if (mode == BandMode.Narrow)
            {
                frequency = 0x1f40;
            }
            else if (mode == BandMode.Wide)
            {
                frequency = 0x3e80;
            }
            byte[]  buffer     = data;
            short[] collection = Codec.Decode(buffer, mode);
            tmp.Clear();
            tmp.AddRange(collection);
            USpeakPoolUtils.Return(collection);
            return(USpeakAudioClipConverter.ShortsToAudioData(tmp.ToArray(), channels, frequency, threeD, gain));
        }
Esempio n. 23
0
        protected override void Decode(IChannelHandlerContext context, IByteBuffer input, List <object> output)
        {
            NettyChannel channel = NettyChannel.GetOrAddChannel(context.Channel, _url, _handler);

            Object msg;

            int saveReaderIndex;

            try
            {
                // decode object.
                do
                {
                    saveReaderIndex = input.ReaderIndex;
                    try
                    {
                        //Console.WriteLine("decode:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
                        msg = _codec.Decode(channel, input);
                        //Console.WriteLine("decoded:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
                    }
                    catch (IOException e)
                    {
                        throw e;
                    }
                    if (msg is DecodeResult result && result == DecodeResult.NeedMoreInput)
                    {
                        input.SetReaderIndex(saveReaderIndex);
                        break;
                    }
                    else
                    {
                        //is it possible to go here ?
                        if (saveReaderIndex == input.ReaderIndex)
                        {
                            throw new IOException("Decode without read data.");
                        }
                        if (msg != null)
                        {
                            output.Add(msg);
                        }
                    }
                } while (input.IsReadable());
            }
Esempio n. 24
0
        /// <summary>
        ///    Loads an image file from the file system.
        /// </summary>
        /// <param name="fileName">Full path to the image file on disk.</param>
        public static Image FromFile(string fileName)
        {
            int pos = fileName.LastIndexOf(".");

            if (pos == -1)
            {
                throw new AxiomException("Unable to load image file '{0}' due to invalid extension.", fileName);
            }

            // grab the extension from the filename
            string ext = fileName.Substring(pos + 1, fileName.Length - pos - 1);

            // find a registered codec for this type
            ICodec codec = CodecManager.Instance.GetCodec(ext);

            // TODO: Need ArchiveManager
            Stream       encoded = ResourceManager.FindCommonResourceData(fileName);
            MemoryStream decoded = new MemoryStream();

            // decode the image data
            ImageCodec.ImageData data = (ImageCodec.ImageData)codec.Decode(encoded, decoded);

            Image image = new Image();

            // copy the image data
            image.height     = data.height;
            image.width      = data.width;
            image.depth      = data.depth;
            image.format     = data.format;
            image.flags      = data.flags;
            image.numMipMaps = data.numMipMaps;

            // stuff the image data into an array
            byte[] buffer = new byte[decoded.Length];
            decoded.Position = 0;
            decoded.Read(buffer, 0, buffer.Length);
            decoded.Close();

            image.SetBuffer(buffer);

            return(image);
        }
Esempio n. 25
0
        private static void CheckCodec <T>(ICodec <T> codec, int count)
            where T : unmanaged
        {
            var data    = Factory.CreateRandomBytes(count * sizeof(T));
            var encoded = new UnsafeBuffer(codec.GetMaxEncodedSize(data.Length));
            var decoded = new UnsafeBuffer(data.Length);

            int length;

            fixed(byte *p = data)
            length = codec.Encode((T *)p, count, encoded.Ptr);

            var result = codec.Decode(encoded.Ptr, length, (T *)decoded.Ptr);

            Assert.AreEqual(count, result, "Mismatch number of decoded data");
            data.Check(decoded.Data);

            decoded.Dispose();
            encoded.Dispose();
        }
        public Task OnServerStarted(IDiResolveReleaseOnlyContainer di)
        {
            _consoleBasedListener = new Thread(() => {
                Thread.CurrentThread.IsBackground = true;

                LogAsReply("listening started");

                while (!_shouldQuit)
                {
                    var rawCmd = _receiveCommand();
                    LogAsReply("received raw command");

                    try {
                        var decoded = _codec.Decode <CommandRequest>(rawCmd);

                        LogAsReply($"successfully decoded command requestId={decoded.Id} type={decoded.Type}");

                        switch (decoded.Type)
                        {
                        case RequestType.StopServer:
                            _shouldQuit = true;
                            break;

                        default: throw new Exception("unsupported RequestType");
                        }
                    } catch (Exception ex) {
                        LogAsReply($"could not decode command because of {ex}");
                    }
                }
            });
            _consoleBasedListener.Start();

            Send(CommandReplyUtil.CreateServerStarted());
            SendFilterInvocation(new FilterInvocation {
                InvType = FilterInvocationType.ServerStarted
            });

            return(Task.CompletedTask);
        }
Esempio n. 27
0
        public static AudioClip DecompressAudioClip(byte[] data, int frequency = 8000, int channels = 1, float gain = 1.0f)
        {
            byte[] d;
            d = unzip(data);

            short[] pcm = Codec.Decode(d);

            tmp.Clear();
            tmp.AddRange(pcm);

            //while (tmp.Count > 1 && Mathf.Abs(tmp[tmp.Count - 1]) <= 10)
            //{
            //    tmp.RemoveAt(tmp.Count - 1);
            //}

            //while (tmp.Count > 1 && Mathf.Abs(tmp[0]) <= 10)
            //{
            //    tmp.RemoveAt(0);
            //}

            return(ShortsToAudioClip(tmp.ToArray(), channels, frequency, gain));
        }
Esempio n. 28
0
        /// <inheritdoc cref="Owasp.Esapi.Interfaces.IEncoder.Canonicalize(IEnumerable&lt;string&gt;, string, bool)" />
        public string Canonicalize(IEnumerable <string> codecNames, string input, bool strict)
        {
            if (codecNames == null)
            {
                throw new ArgumentNullException("codecNames");
            }
            if (string.IsNullOrEmpty(input))
            {
                return(input);
            }

            String working    = input;
            ICodec codecFound = null;
            int    mixedCount = 1;
            int    foundCount = 0;
            bool   clean      = false;

            while (!clean)
            {
                clean = true;
                // try each codec and keep track of which ones work
                foreach (string codecName in codecNames)
                {
                    if (string.IsNullOrEmpty(codecName))
                    {
                        continue;
                    }

                    String old   = working;
                    ICodec codec = codecs[codecName];
                    working = codec.Decode(working);
                    if (!old.Equals(working))
                    {
                        if (codecFound != null && codecFound != codec)
                        {
                            mixedCount++;
                        }
                        codecFound = codec;
                        if (clean)
                        {
                            foundCount++;
                        }
                        clean = false;
                    }
                }
            }
            // do strict tests and handle if any mixed, multiple, nested encoding were found
            if (foundCount >= 2 && mixedCount > 1)
            {
                if (strict)
                {
                    throw new IntrusionException(EM.Encoder_InputValidationFailure, string.Format(EM.Encoder_MultipleMixedEncoding2, foundCount, mixedCount));
                }
                else
                {
                    logger.Warning(LogEventTypes.SECURITY, string.Format(EM.Encoder_MultipleMixedEncoding2, foundCount, mixedCount));
                }
            }
            else if (foundCount >= 2)
            {
                if (strict)
                {
                    throw new IntrusionException(EM.Encoder_InputValidationFailure, string.Format(EM.Encoder_MultipleEncoding1, foundCount));
                }
                else
                {
                    logger.Warning(LogEventTypes.SECURITY, string.Format(EM.Encoder_MultipleEncoding1, foundCount));
                }
            }
            else if (mixedCount > 1)
            {
                if (strict)
                {
                    throw new IntrusionException(EM.Encoder_InputValidationFailure, string.Format(EM.Encoder_MixedEncoding1, mixedCount));
                }
                else
                {
                    logger.Warning(LogEventTypes.SECURITY, string.Format(EM.Encoder_MixedEncoding1, mixedCount));
                }
            }
            return(working);
        }