public SUDMSGAddModDel Decode(BinaryData encodedData) { return (new SUDMSGAddModDel( nidDecoder.Decode(encodedData.Take(4)), nidDecoder.Decode(encodedData.Take(4, 4)))); }
public SUDMSGSpam Decode(BinaryData encodedData) { return (new SUDMSGSpam( nidDecoder.Decode(encodedData.Take(4)), nidDecoder.Decode(encodedData.Take(4, 4)))); }
/// <summary> /// Decodes the given encoded data. /// </summary> /// <param name="inData">The encoded data. Can be multiple frames.</param> /// <param name="inOffset">Start offset where to read the encoded data from.</param> /// <param name="inCount">The number of bytes to decode.</param> /// <param name="outData">The output of the decoded data in samples.</param> /// <param name="outOffset">Start offset where to start writing the decoded samples from.</param> /// <param name="lostFrame">Indicates if we are decoding a lost frame. Alternatively the <paramref name="inData"/> parameter can be <value>null</value>.</param> /// <returns>The number of samples decoded.</returns> public int Decode(byte[] inData, int inOffset, int inCount, short[] outData, int outOffset, bool lostFrame) { if (decodedData.Length < outData.Length * 2) { // resize the decoded data buffer decodedData = new float[outData.Length * 2]; } if (lostFrame || inData == null) { decoder.Decode(null, decodedData); for (int i = 0; i < frameSize; i++, outOffset++) { outData[outOffset] = ConvertToShort(decodedData[i]); } return(frameSize); } bits.ReadFrom(inData, inOffset, inCount); int samplesDecoded = 0; while (decoder.Decode(bits, decodedData) == 0) { for (int i = 0; i < frameSize; i++, outOffset++) { outData[outOffset] = ConvertToShort(decodedData[i]); } samplesDecoded += frameSize; } return(samplesDecoded); }
private void ButtonRunImage_Click(object sender, EventArgs e) { if (pictureBoxUploadedImage == null || pictureBoxUploadedImage.Image == null) { MessageBox.Show("Upload an image first"); return; } string binaryUserInput = BitUtils.ImageToBinaryString(pictureBoxUploadedImage.Image); // Užkodavimas, siuntimas kanalu ir dekodavimas --------------------------------- string encoderOutput = _convolutionalEncoder.Encode(binaryUserInput); _simpleChannel.SetNoiseLevel((double)numericUpDownNoiseLevel.Value); int headerSize = binaryUserInput.Length - Image.GetPixelFormatSize(pictureBoxUploadedImage.Image.PixelFormat) * (pictureBoxUploadedImage.Image.Width * pictureBoxUploadedImage.Image.Height); // Pagal sąsūkos kodą užkodavus pranešimą jo ilgis yra 2k + 12, todėl atitinkamai headerio dydis pailgėja taip pat. string channelOutput = _simpleChannel.AddNoise(encoderOutput, (headerSize + 1) * 2 + 12); string decoderOutput = _convolutionalDecoder.Decode(channelOutput); pictureBoxDecoderOutput.Image = BitUtils.BinaryStringToImage(decoderOutput); // Tik siuntimas kanalu --------------------------------------------------------- channelOutput = _simpleChannel.AddNoise(binaryUserInput, headerSize + 1); pictureBoxChannelOutput.Image = BitUtils.BinaryStringToImage(channelOutput); }
/// <summary> /// This is where the actual decoding takes place. /// </summary> /// <param name="lost"> /// true if the Speex packet has been lost. /// </param> private void processData(bool lost) { /* decode the bitstream */ if (lost) { decoder.Decode(null, decodedData); } else { decoder.Decode(bits, decodedData); } if (channels == 2) { decoder.DecodeStereo(decodedData, frameSize); } for (int i = 0; i < frameSize * channels; i++) { if (decodedData[i] > 32767.0f) { decodedData[i] = 32767.0f; } else if (decodedData[i] < -32768.0f) { decodedData[i] = -32768.0f; } } outputSize = frameSize * channels; }
public SUDFLDAddMov Decode(BinaryData encodedData) { return (new SUDFLDAddMov( nidDecoder.Decode(encodedData.Take(4)), nidDecoder.Decode(encodedData.Take(4, 4)), encodedData.Take(8, 4).ToInt32(), encodedData.Take(12, 4).ToInt32())); }
static void Main(string[] args) { Console.WriteLine("Введите адрес файла для кодировки"); string fileName = Console.ReadLine(); DateTime startEncode = DateTime.Now; Encoder encoder = new Encoder(fileName); encoder.Encode(); TimeSpan tsEncode = DateTime.Now - startEncode; DisplayCodeInformation(encoder); encoder.WriteToFile("myFile.bin"); DateTime startDecode = DateTime.Now; string decoderType = ConfigurationManager.AppSettings.Get("DecoderType"); IDecoder decoder = DecoderCreator.Create(encoder.CodeToChar, "myFile.bin", encoder.TextLength, decoderType); decoder.Decode(); TimeSpan tsDecode = DateTime.Now - startDecode; Console.WriteLine("Время выполнения кодировки/декодировки: " + tsEncode.ToString(@"ss\.ffff") + "/" + tsDecode.ToString(@"ss\.ffff")); decoder.SaveToText("text.txt", Encoding.GetEncoding(1251)); Console.ReadLine(); }
private static string Load(string className) { string line = ""; var path = PersistentDataPath + className + ".json"; if (!System.IO.File.Exists(path)) { return(""); } StreamReader sr = null; try { sr = new StreamReader(path); } catch (Exception) { Debug.Log($"{className}.json not found."); sr.Close(); return(""); } line = sr.ReadLine(); sr.Close(); var decodeParam = _decoder.Decode(line); return(decodeParam); }
public void ATMController_EventIsRaised_DataIsPassedFromDecoderToFilter() { // Arrange _fakeEventArgs = new RawTransponderDataEventArgs(new List <string>()); // Act //Fake decoder should return fake Trackdata when called with fakeEventArgs _fakeDecoder.Decode(_fakeEventArgs).Returns(_fakeTrackData = new List <TrackData> { new TrackData("AYE334", 12345, 54321, 5000, new DateTime(year: 2000, month: 10, day: 9, hour: 8, minute: 7, second: 6, millisecond: 5)), new TrackData("BYE331", 12121, 23232, 5001, new DateTime(year: 2001, month: 11, day: 10, hour: 9, minute: 8, second: 7, millisecond: 6)), new TrackData("HMM221", 34343, 45454, 5002, new DateTime(year: 2002, month: 12, day: 11, hour: 10, minute: 9, second: 8, millisecond: 7)) }); //Raise event _fakeReceiver.TransponderDataReady += Raise.EventWith(new object(), _fakeEventArgs); // Assert _fakeTrackDataFilter.Received().Filter(Arg.Is <List <TrackData> >(x => x[0].Tag == "AYE334" && x[0].X == 12345 && x[0].Y == 54321 && x[0].Altitude == 5000 && x[0].Timestamp.Year == 2000 && x[0].Timestamp.Month == 10 && x[0].Timestamp.Day == 9 && x[0].Timestamp.Hour == 8 && x[0].Timestamp.Minute == 7 && x[0].Timestamp.Second == 6 && x[0].Timestamp.Millisecond == 5 && x[1].Tag == "BYE331" && x[1].X == 12121 && x[1].Y == 23232 && x[1].Altitude == 5001 && x[1].Timestamp.Year == 2001 && x[1].Timestamp.Month == 11 && x[1].Timestamp.Day == 10 && x[1].Timestamp.Hour == 9 && x[1].Timestamp.Minute == 8 && x[1].Timestamp.Second == 7 && x[1].Timestamp.Millisecond == 6 && x[2].Tag == "HMM221" && x[2].X == 34343 && x[2].Y == 45454 && x[2].Altitude == 5002 && x[2].Timestamp.Year == 2002 && x[2].Timestamp.Month == 12 && x[2].Timestamp.Day == 11 && x[2].Timestamp.Hour == 10 && x[2].Timestamp.Minute == 9 && x[2].Timestamp.Second == 8 && x[2].Timestamp.Millisecond == 7 )); }
public void Decode(IEnumerable <IFieldInfoEx> fields) { if (fields == null) { return; } var decodeFields = from item in fields where item.Decoder != null && item.Decoder.Type != DecoderType.None select item; if (Decoder == null) { Decoder = new ObjectDecoderContainer(); } foreach (var item in decodeFields) { IDecoder coder = GetDecoder(item.Decoder); if (coder != null) { IDecoderItem decodeItem = coder.Decode( MainObject.MemberValue(item.NickName).ConvertToString()); if (decodeItem != null) { Decoder.Add(item.NickName, decodeItem); } } } }
private unsafe void Load(CancellationToken token) { sw.Restart(); try { token.ThrowIfCancellationRequested(); decoder.Device = device; lock (streamLock) { decoder.Load(memoryStream); } token.ThrowIfCancellationRequested(); description = decoder.Description; LoadingCompleted(description); decoder.Decode(); token.ThrowIfCancellationRequested(); Loaded = true; } catch (OperationCanceledException) { } catch (Exception e) { System.Diagnostics.Debug.WriteLine("load: {0}", e); throw e; } DecodeTime = sw.Elapsed.TotalMilliseconds; }
private void Read(string address, OpResult result, IAddressableEncoder encoder, IDecoder decoder, Action <OpResult, IEncoder, IDecoder> dataGotAction) { if (result.CheckNotNullOrWhiteSpace(address, SR.ArgumentIsNullOrEmpty)) { FinsFrame frame = NewFrame(); frame.MRC = 01; frame.SRC = 01; if (result.CheckTrue(encoder.FillAddress(address), SR.WrongAddressFormat)) { frame.Content = encoder.Encode(); var buffer = frame.Encode(); try { int count = _client.Send(buffer, buffer.Length); buffer = _client.Receive(ref _remoteEndpoint); var decodeFrame = new FinsFrame(); if (result.CheckTrue(decodeFrame.Decode(buffer), SR.DecodeError)) { if (result.CheckTrue(decoder.Decode(decodeFrame.Content), SR.DecodeError)) { dataGotAction?.Invoke(result, encoder, decoder); } } } catch (Exception ex) { result.SetException(ex, SR.CallServiceException); } } } }
public SUDFLDModDel Decode(BinaryData encodedData) { return (new SUDFLDModDel( nidDecoder.Decode(encodedData.Take(4)), encodedData.Take(4, 4).ToInt32())); }
public string Decode(byte[] byteArray) { byte[] decodedData = decoder.Decode(byteArray); string retVal = System.Text.Encoding.UTF8.GetString(decodedData); return(retVal); }
public void HandleAudioDataReceived(object sender, VoipDataPacket e) { if (!enabled) { return; } if (e.Data != null && e.DataLength > 0) { //if (e.Data.Length > e.DataLength) // Plugin.Log?.Debug($"Data length is {e.Data.Length}, expected length is {e.DataLength}"); if (e.Data.Length < e.DataLength) { Plugin.Log?.Warn($"Data length of '{e.Data.Length}' is less than the expected length of '{e.DataLength}'"); } float[] floatData = FloatAryPool.Rent(4096); int length = Decoder.Decode(e.Data, 0, e.DataLength, floatData, 0); //Plugin.Log?.Debug($"Playing fragment, length {length}x{Decoder.Channels}"); PlayVoIPFragment(floatData, length * Decoder.Channels, e.Index); FloatAryPool.Return(floatData); } else { Plugin.Log?.Warn($"HandleAudioDataReceived {(e.Data == null ? "Data was null" : $"DataLength: {e.DataLength}")}"); } }
public void Update(IB regionOffset, Func <TType, TType> processRegion) { var originalPosition = stream.Position; try { stream.Position = regionOffset; var rawRegion = new byte[typeSize]; stream.Read(rawRegion, 0, typeSize); var type = typeDecoder.Decode(BinaryData.OfValue(rawRegion)); var updatedType = processRegion(type); stream.Position = regionOffset; var encodedType = typeEncoder.Encode(updatedType); stream.Write(encodedType.Value, 0, encodedType.Value.Length); } finally { stream.Position = originalPosition; } }
public TM Resolve <TM>(IBasicProperties basicProperties, ReadOnlyMemory <byte> body) where TM : IMessage { if (basicProperties is null) { throw new ArgumentNullException(nameof(basicProperties)); } if (basicProperties.Headers is null) { throw new ArgumentNullException(nameof(basicProperties), "message headers are missing"); } if (!basicProperties.Headers.TryGetValue(HeaderNames.MessageType, out var tmp) || tmp is not byte[] messageTypeBytes || messageTypeBytes is null) { throw new ArgumentException("invalid message type"); } var messageTypeName = Encoding.UTF8.GetString(messageTypeBytes); var dataType = _typeResolver.Resolve(messageTypeName); var decodedObj = _decoder.Decode(body, dataType); if (decodedObj is not TM message) { throw new ArgumentException($"type '{messageTypeName}' is not a valid message"); } return(message); }
//Run every time new data is present private void Update(RawTransponderDataEventArgs e) { //Decode Data List <TrackData> trackData = _decoder.Decode(e); //Filter data trackData = _filter.Filter(trackData); //Update existing flight data _data = _flightCalculator.Calculate(_data, trackData); //Collision Detect Tuple <List <string>, List <string> > collisionResult = _collisionDetector.SeperationCheck(trackData); List <string> collisionTags = collisionResult.Item1; List <string> displayCollisionList = collisionResult.Item2; //Set CollisionFlag on flights foreach (KeyValuePair <string, FlightData> entry in _data) { entry.Value.CollisionFlag = collisionTags.Contains(entry.Value.Tag); } //Display Data _display.Clear(); _display.Render(_data, displayCollisionList); }
public SLEntry Decode(BinaryData encodedData) { var parser = BinaryDataParser.OfValue(encodedData); var localNID = parser.TakeAndSkip(8); var subnodeBID = parser.TakeAndSkip(8); var subnodeNID = parser.TakeAndSkip(8); return (new SLEntry( NID.OfValue(localNID.Take(4)), bidDecoder.Decode(subnodeBID), bidDecoder.Decode(subnodeNID))); }
public void Run() { Bitmap bitmap = null; try { if (_decoder.CanProcessImage == null || !_decoder.CanProcessImage()) { _backgroundHandler.Post(new ImageDecoder(_backgroundHandler, _surfaceView)); return; } bitmap = _surfaceView.GetBitmap(_decoder.ImageSizeX, _decoder.ImageSizeY); var result = _decoder.Decode(bitmap); bitmap.Recycle(); if (_decoder.FinishProcessImage(result)) { return; } } catch (System.Exception ex) { bitmap?.Recycle(); _decoder.HandleExceptionFromProcessImage?.Invoke(ex); } _backgroundHandler.Post(new ImageDecoder(_backgroundHandler, _surfaceView)); }
public TType TakeAndSkip <TType>(int count, IDecoder <TType> typeDecoder) { var buffer = new byte[count]; stream.Read(buffer, 0, count); return(typeDecoder.Decode(BinaryData.OfValue(buffer))); }
/// <inheritdoc /> public FieldElement[] Decode(FieldElement[] noisyCodeword) => _decoder.Decode( CodewordLength, InformationWordLength, CodeDistance, _generatingPolynomial, TransformNoisyCodeword(noisyCodeword) ) .GetCoefficients(InformationWordLength - 1);
/// <inheritdoc cref="Decompress"/> public void Decompress(Stream input, Stream output) { if (_decoder == null) { throw new InvalidOperationException("The decoder is not set."); } _decoder.Decode(input, output); }
public InternalDataBlock LoadNode(LBBTEntry nodeReference) { return (cache .GetOrAdd( nodeReference.BlockReference.BlockId, () => internalDataBlockDecoder.Decode(dataBlockReader.Read(nodeReference.BlockReference.ByteIndex.Value, nodeReference.GetBlockSize()))) .Value); }
private void DecodeButton_Click(object sender, RoutedEventArgs e) { if (string.IsNullOrEmpty(DataText.Text)) { DecodeText.Clear(); return; } DecodeText.Text = decoder.Decode(buff); }
public string Decode(string payload, IDecoder decoder) { // Decode Span <byte> bytes = decoder.Decode(payload); // Convert to string string result = Encoding.ASCII.GetString(bytes); return(result); }
public void OnPlaneDecodedEventWasRaised() { var wasCalled = false; Uut.PlaneDecodedEvent += (o, e) => wasCalled = true; //lambda expression to subscribe on the event //Call Decode with a empty List only tests if the event is raised as it then doesn't use the foreach loop. Uut.Decode(new object(), new RawTransponderDataEventArgs(Substitute.For <List <string> >())); Assert.True(wasCalled); }
private void Decode(long offset, string key, string jsonMessage, BlockingCollection <DecodedMessage> decodedMessages) { Console.WriteLine($"Raw message consumed with offset: {offset}, key: {key}"); var rawBusMessage = JsonConvert.DeserializeObject <RawBusMessage>(jsonMessage); var decoded = _decoder.Decode(rawBusMessage); foreach (var decodedMessage in decoded) { decodedMessages.Add(decodedMessage); // blocks once bounded capacity reached } }
public long Run(IDataSource source, IEncoder encoder, IDecoder decoder, long msgCount, bool debug) { long totalBytesTransmitted = 0; for (long i = 0; i < msgCount; i++) { var sourceData = source.GetNextDataPoint(); var encodedData = encoder.Encode(sourceData); // This is where the data is normally transmitted via network totalBytesTransmitted += encodedData.LongLength; var decodedData = decoder.Decode(encodedData); var areEqual = IotDevice.AreEquals(sourceData, decodedData, false); if (!areEqual || debug) { Console.WriteLine(); Console.WriteLine("##########################################################"); Console.WriteLine($"Message number: {i+1}"); Console.WriteLine(); Console.WriteLine("source data:"); Console.WriteLine(sourceData); Console.WriteLine(); Console.WriteLine("encoded data:"); Console.WriteLine(BitConverter.ToString(encodedData).Replace("-", "")); Console.WriteLine(); Console.WriteLine("decoded data:"); Console.WriteLine(decodedData); Console.WriteLine(); if (!areEqual) { // run this again to get debug outputs IotDevice.AreEquals(sourceData, decodedData, true); } Console.WriteLine($"Encoding/Decoding successful: {areEqual}"); } if (debug) { Console.WriteLine("Press any key to send the next message."); Console.ReadKey(); } } return(totalBytesTransmitted); }
/// <summary> /// Try read next array item.. /// </summary> /// <param name="reader">The json reader.</param> /// <param name="decoder">The decoder.</param> /// <param name="value">The value of the array item.</param> /// <returns>If succeeded.</returns> private static bool TryReadArrayItem(IJsonReader reader, IDecoder <T> decoder, out T value) { value = default(T); while (!reader.IsEndArray) { value = decoder.Decode(reader); return(true); } return(false); }
/// <summary> /// Computes the spectogram of an audio file. /// </summary> /// <param name="decoder">The <see cref="IDecoder"/> instance.</param> /// <returns>Chroma image.</returns> public static Image ComputeSpectrogram(IDecoder decoder) { int numBands = 72; var image = new Image(numBands); var image_builder = new ImageBuilder(image); var chroma = new Spectrum(numBands, MIN_FREQ, MAX_FREQ, FRAME_SIZE, SAMPLE_RATE, image_builder); var fft = new FFT(FRAME_SIZE, OVERLAP, chroma, new LomontFFTService()); var processor = new AudioProcessor(SAMPLE_RATE, fft); processor.Reset(decoder.SampleRate, decoder.Channels); decoder.Decode(processor, 120); processor.Flush(); return image; }
//static int MAX_FILTER_WIDTH = 20; public static Image Compute(string file, IDecoder decoder) { int numBands = 72; Image image = new Image(numBands); ImageBuilder image_builder = new ImageBuilder(image); Spectrum chroma = new Spectrum(numBands, MIN_FREQ, MAX_FREQ, FRAME_SIZE, SAMPLE_RATE, image_builder); FFT fft = new FFT(FRAME_SIZE, OVERLAP, chroma); AudioProcessor processor = new AudioProcessor(SAMPLE_RATE, fft); processor.Reset(decoder.SampleRate, decoder.Channels); decoder.Decode(processor, 120); processor.Flush(); //ExportImage(image, name, 0.5); return image; }
/// <summary> /// Computes the chromagram of an audio file. /// </summary> /// <param name="decoder">The <see cref="IDecoder"/> instance.</param> /// <returns>Chroma image.</returns> public static Image ComputeChromagram(IDecoder decoder) { var image = new Image(12); var image_builder = new ImageBuilder(image); var chroma_normalizer = new ChromaNormalizer(image_builder); var chroma_filter = new ChromaFilter(ChromaFilterCoefficients, chroma_normalizer); var chroma = new Chroma(MIN_FREQ, MAX_FREQ, FRAME_SIZE, SAMPLE_RATE, chroma_filter); var fft = new FFT(FRAME_SIZE, OVERLAP, chroma, new LomontFFTService()); var processor = new AudioProcessor(SAMPLE_RATE, fft); processor.Reset(decoder.SampleRate, decoder.Channels); decoder.Decode(processor, 120); processor.Flush(); return image; }
public static Image Compute(string file, IDecoder decoder) { Image image = new Image(12); ImageBuilder image_builder = new ImageBuilder(image); ChromaNormalizer chroma_normalizer = new ChromaNormalizer(image_builder); ChromaFilter chroma_filter = new ChromaFilter(ChromaFilterCoefficients, chroma_normalizer); //Chroma chroma = new Chroma(MIN_FREQ, MAX_FREQ, FRAME_SIZE, SAMPLE_RATE, &chroma_normalizer); Chroma chroma = new Chroma(MIN_FREQ, MAX_FREQ, FRAME_SIZE, SAMPLE_RATE, chroma_filter); FFT fft = new FFT(FRAME_SIZE, OVERLAP, chroma); AudioProcessor processor = new AudioProcessor(SAMPLE_RATE, fft); processor.Reset(decoder.SampleRate, decoder.Channels); decoder.Decode(processor, 120); processor.Flush(); //ExportImage(image, name); return image; }