示例#1
0
            void ReaderController.ReaderStateChangedListener.onDecodeError(DecodeResult decodeResult)
            {
                NetTracer.Warning(string.Format("The decode error occured : {0}", decodeResult.ToString()));

                // Restart the device to capture the swipe information again.
                this.StartReader();
            }
示例#2
0
        public async Task <string> Decode(IFormFile wave)
        {
            if (wave == null)
            {
                DecodeResult errorResult = new DecodeResult
                {
                    Id      = "",
                    Text    = "",
                    Message = "Usage: POST <host_name>/Decoding/Decode\n" +
                              "Content-Disposition: form-data; name=\"wave\"; filename=\"your.wav\"\n" +
                              "Content-Type: audio/x-wav\n\n" +
                              "<binary_contents>"
                };
                return(JsonConvert.SerializeObject(errorResult, Formatting.Indented));
            }

            Speech speech = new Speech();

            speech.Wave = new byte[wave.Length];
            wave.CopyTo(new MemoryStream(speech.Wave));
            speech.SpeechId = Guid.NewGuid().ToString();
            DecodeResult result = await _decoder.DecodeAsync(speech);

            return(JsonConvert.SerializeObject(result, Formatting.Indented));
        }
示例#3
0
    //Function for decoding back from encoded data
    public DecodeResult Decode(byte[] data)
    {
        int _width  = data[0];
        int _height = data[1];

        //create BGRA pixel array
        byte[] _pixels = new byte[_width * _height * 4];

        //Set pixels
        for (int i = 0; i < _width * _height; ++i)
        {
            _pixels[i * 4]     = data[2 + i];
            _pixels[i * 4 + 1] = data[2 + i];
            _pixels[i * 4 + 2] = data[2 + i];
            _pixels[i * 4 + 3] = 0xFF; //Full alpha
        }

        //Create result container
        DecodeResult _result = new DecodeResult();

        _result.pixels = _pixels;
        _result.width  = _width;
        _result.height = _height;

        return(_result);
    }
示例#4
0
        private List <DecodeResult> DecodeResult(string result, SpiderFormula formula)
        {
            List <DecodeResult> list = new List <DecodeResult>();
            string text = result.Substring(result.IndexOf("<div class=\"results\">"))
                          .Replace("\r", " ").Replace("\\n", " ").Replace("\n", " ")
                          .Replace("<em>", "").Replace("</em>", "")
                          .Replace("<!--awbg5-->", "").Replace("<!--red_beg-->", "")
                          .Replace("<!--red_end-->", "");
            var matches = regex.Matches(text);

            if (matches == null)
            {
                return(null);
            }
            foreach (Match match in matches)
            {
                var d = new DecodeResult();
                d.searchengine = SearchEngineName;
                d.ipaddress    = match.Groups[3].Value.ToString();
                d.no           = match.Groups[2].Value.ToString();
                d.title        = match.Groups[4].Value.ToString();
                list.Add(d);
            }
            return(list);
        }
示例#5
0
        private static DecodeResult ProcessDecode(Image <Rgba32> image)
        {
            var decodeResult = new DecodeResult();
            var source       = new ImageSharpLuminanceSource <Rgba32>(image);
            var reader       = new BarcodeReader(null, null, ls => new GlobalHistogramBinarizer(ls))
            {
                AutoRotate  = true,
                TryInverted = true,
                Options     = new DecodingOptions
                {
                    TryHarder       = true,
                    PossibleFormats = new List <BarcodeFormat>
                    {
                        BarcodeFormat.ITF
                        //BarcodeFormat.EAN_8,
                        //BarcodeFormat.CODE_39,
                        //BarcodeFormat.UPC_A
                    }
                }
            };
            var result = reader.Decode(source);

            if (result != null)
            {
                decodeResult.ItemFound    = true;
                decodeResult.BarcodeType  = result.BarcodeFormat.ToString();
                decodeResult.BarcodeValue = result.Text;
            }

            return(decodeResult);
        }
示例#6
0
        private async Task <DecodeResult> DecodyAsyncImpl(Speech speech)
        {
            Stopwatch sw = new Stopwatch();

            sw.Restart();

            DecodeResult decodeResult;

            try
            {
                AutoResetEvent finishEvent = queue.RegisterEvent(speech.SpeechId);
                redis.Push(speech);
                bool success = await Task.Run(() =>
                {
                    bool result = finishEvent.WaitOne(decodingTimeOut);
                    if (!result)
                    {
                        _logger.Error($"Decoding timeout for Speech {speech.SpeechId}");
                        return(false);
                    }
                    return(true);
                });

                if (!success)
                {
                    return(new DecodeResult {
                        Id = speech.SpeechId, Message = "TimeOut"
                    });
                }
                decodeResult = queue.PopResult(speech.SpeechId);

                /*
                 * if (new Random().NextDouble() < 0.5) {
                 *  throw new Exception("mock redis timeout");
                 * }*/
            }
            catch (StackExchange.Redis.RedisTimeoutException e)
            {
                decodeResult = new DecodeResult {
                    Id = speech.SpeechId, Message = "RedisTimeOut"
                };
                _logger.Fatal("[" + speech.SpeechId + "]: " + e.Message);
            }
            catch (Exception e)
            {
                decodeResult = new DecodeResult {
                    Id = speech.SpeechId, Message = "Unknown error"
                };
                _logger.Fatal("[" + speech.SpeechId + "]: " + e.Message);
            }

            timeCostRecord.Enqueue(sw.ElapsedMilliseconds);
            if (timeCostRecord.Count > 100)
            {
                timeCostRecord.TryDequeue(out _);
            }
            _logger.Info($"RTT {speech.SpeechId}: {sw.ElapsedMilliseconds}ms");
            _logger.Info($"Average RTT: {(1.0 * timeCostRecord.Sum() / timeCostRecord.Count)}ms");
            return(decodeResult);
        }
示例#7
0
        static async void TestRemote()
        {
            ThreadPool.SetMinThreads(250, 250);

            var config = AsyncDecoderConfig.FromFile("./async_decoder_config.json");

            config.EnableFakeDecoder = false;
            IDecoder decoder = new AsyncDecoder(config);

            byte[] mockWave = new byte[] { 1, 2, 3, 4 };
            IList <Task <DecodeResult> > list = new List <Task <DecodeResult> >();

            for (int i = 0; i < 200; i++)
            {
                Task <DecodeResult> task = decoder.DecodeAsync(new Speech {
                    SpeechId = i.ToString(), Wave = mockWave
                });
                //Thread.Sleep(2);
                list.Add(task);
            }
            for (int i = 0; i < 200; i++)
            {
                DecodeResult result = await list[i];
                Console.WriteLine(result.Text + "|" + result.Message);
            }
        }
示例#8
0
        /*	public byte[] decode(QRCodeImage qrCodeImage) throws DecodingFailedException{
         *  canvas.println("Decoding started.");
         *  int[][] intImage = imageToIntArray(qrCodeImage);
         *  try {
         *  QRCodeImageReader reader = new QRCodeImageReader();
         *  qrCodeSymbol = reader.getQRCodeSymbol(intImage);
         *  } catch (SymbolNotFoundException e) {
         *  throw new DecodingFailedException(e.getMessage());
         *  }
         *  canvas.println("Created QRCode symbol.");
         *  canvas.println("Reading symbol.");
         *  canvas.println("Version: " + qrCodeSymbol.getVersionReference());
         *  canvas.println("Mask pattern: " + qrCodeSymbol.getMaskPatternRefererAsString());
         *  int[] blocks = qrCodeSymbol.getBlocks();
         *  canvas.println("Correcting data errors.");
         *  int[] dataBlocks = correctDataBlocks(blocks);
         *  try {
         *  byte[] decodedByteArray =
         *  getDecodedByteArray(dataBlocks, qrCodeSymbol.getVersion());
         *  canvas.println("Decoding finished.");
         *  return decodedByteArray;
         *  } catch (InvalidDataBlockException e) {
         *  throw new DecodingFailedException(e.getMessage());
         *  }
         * }*/

        public virtual sbyte[] decodeBytes(QRCodeImage qrCodeImage)
        {
            Point[] adjusts = AdjustPoints;
            System.Collections.ArrayList results = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10));
            numTryDecode = 0;

            while (numTryDecode < adjusts.Length)
            {
                try
                {
                    DecodeResult result = decode(qrCodeImage, adjusts[numTryDecode]);
                    if (result.isCorrectionSucceeded)
                    {
                        return(result.DecodedBytes);
                    }
                    else
                    {
                        results.Add(result);
                        canvas.println("Decoding succeeded but could not correct");
                        canvas.println("all errors. Retrying..");
                    }
                }
                catch (DecodingFailedException dfe)
                {
                    if (dfe.Message.IndexOf("Finder Pattern") >= 0)
                    {
                        throw dfe;
                    }
                }
                finally
                {
                    numTryDecode += 1;
                }
            }

            if (results.Count == 0)
            {
                throw new DecodingFailedException("Give up decoding");
            }

            int minErrorIndex = -1;
            int minError      = System.Int32.MaxValue;

            for (int i = 0; i < results.Count; i++)
            {
                DecodeResult result = (DecodeResult)results[i];
                if (result.numCorrectionFailures < minError)
                {
                    minError      = result.numCorrectionFailures;
                    minErrorIndex = i;
                }
            }
            canvas.println("All trials need for correct error");
            canvas.println("Reporting #" + (minErrorIndex) + " that,");
            canvas.println("corrected minimum errors (" + minError + ")");

            canvas.println("Decoding finished.");
            return(((DecodeResult)results[minErrorIndex]).DecodedBytes);
        }
示例#9
0
        public NannListItem(DecodeResult decodeResult)
        {
            InitializeComponent();

            this.mainText.Text = "【" + decodeResult.searchengine + "】" + decodeResult.keyword + "\r\n【" + decodeResult.no + "】"
                                 + decodeResult.title
                                 + "\r\n" + decodeResult.ipaddress;
        }
示例#10
0
        private async void EditorPreview_Checked(object sender, RoutedEventArgs e)
        {
            if (EditorText.Visibility == Visibility.Visible)
            {
                try
                {
                    lastDecodeResult = await decoder.decode(ASCIIEncoding.ASCII.GetBytes(EditorText.Text));
                }
                catch
                {
                    var           loader             = new ResourceLoader();
                    var           warningTilte       = loader.GetString("DecodeFailureTitle");
                    var           warningMesage      = loader.GetString("DecodeFailureMessage");
                    var           ok                 = loader.GetString("Ok");
                    MessageDialog decodeFailedDialog = new MessageDialog(warningMesage, warningTilte);
                    decodeFailedDialog.Commands.Add(new UICommand(ok));
                    decodeFailedDialog.DefaultCommandIndex = 0;
                    await decodeFailedDialog.ShowAsync();

                    return;
                }
            }
            else if (EditorHex.Visibility == Visibility.Visible)
            {
                try
                {
                    lastDecodeResult = await decoder.decode(EditorHex.Bytes);
                }
                catch (Exception)
                {
                    var           loader             = new ResourceLoader();
                    var           warningTilte       = loader.GetString("DecodeFailureTitle");
                    var           warningMesage      = loader.GetString("DecodeFailureMessage");
                    var           ok                 = loader.GetString("Ok");
                    MessageDialog decodeFailedDialog = new MessageDialog(warningMesage, warningTilte);
                    decodeFailedDialog.Commands.Add(new UICommand(ok));
                    decodeFailedDialog.DefaultCommandIndex = 0;
                    await decodeFailedDialog.ShowAsync();

                    return;
                }
            }
            cbm   = CanvasBitmap.CreateFromBytes(EditorCanvas, lastDecodeResult.Bytes, lastDecodeResult.Width, lastDecodeResult.Height, DirectXPixelFormat.B8G8R8A8UIntNormalized);
            brush = new CanvasImageBrush(EditorCanvas, cbm)
            {
                Interpolation = CanvasImageInterpolation.NearestNeighbor
            };
            EditorCanvas.Width  = lastDecodeResult.Width;
            EditorCanvas.Height = lastDecodeResult.Height;

            EditorCanvas.Visibility = Visibility.Visible;
            EditorEditGrid.RowDefinitions[editorRow].Height = new GridLength(0, GridUnitType.Pixel);
            EditorEditGrid.RowDefinitions[2].Height         = new GridLength(1, GridUnitType.Star);
            this.Keyboard.Visibility = Visibility.Collapsed;
            EditorCanvas.Invalidate();
        }
示例#11
0
        private void Decode(IEnumerable <Bitmap> bitmaps)
        {
            _timeStart = DateTime.Now.Ticks;
            results.Clear();
            var fileName = new FileInfo(_config.FilePath).Name;

            var i = 1;

            foreach (var bitmap in bitmaps)
            {
                var singleStart = DateTime.Now.Ticks;

                // https://github.com/micjahn/ZXing.Net/issues/132 requires bindings package
                // as here: https://stackoverflow.com/questions/28561772/c-sharp-with-zxing-net-decoding-the-qr-code
                var imageAsLuminance = new BitmapLuminanceSource(bitmap);

                try
                {
                    var mappedResult = CallDecode(imageAsLuminance, singleStart);

                    var singleTime = new TimeSpan(DateTime.Now.Ticks - singleStart);
                    mappedResult.FileName   = fileName;
                    mappedResult.Duration   = singleTime;
                    mappedResult.PageInTiff = i;
                    results.Add(mappedResult);
                }
                catch (Exception)
                {
                    string message      = "Decoder failed with read exception.";
                    var    singleTime   = new TimeSpan(DateTime.Now.Ticks - singleStart);
                    var    mappedResult = new DecodeResult();
                    mappedResult.Success    = false;
                    mappedResult.Note       = message;
                    mappedResult.FileName   = fileName;
                    mappedResult.Duration   = singleTime;
                    mappedResult.PageInTiff = i;
                    results.Add(mappedResult);
                }

                i++;
            }

            // save analysis
            var timerStop = DateTime.Now.Ticks;

            statistics.FileName        = fileName;
            statistics.ExecuteDuration = new TimeSpan(timerStop - _timeStart);
            statistics.Results         = results;

            if (results == null)
            {
                statistics.Note = "No barcode found in image";
            }
        }
        public void SetImageInfo(DecodeResult imageInfo)
        {
            this.imageInfo   = imageInfo;
            this.initialZoom = imageInfo.CurrentZoom;

            this.Background = new SolidColorBrush(Colors.Transparent);

            this.ManipulationMode =
                ManipulationModes.System |
                ManipulationModes.Scale;
            isInfoSet = true;
        }
示例#13
0
        public virtual sbyte[] decodeBytes(QRCodeImage qrCodeImage)
        {
            Point[]   adjustPoints = AdjustPoints;
            ArrayList arrayList    = ArrayList.Synchronized(new ArrayList(10));

            while (numTryDecode < adjustPoints.Length)
            {
                try
                {
                    DecodeResult decodeResult = decode(qrCodeImage, adjustPoints[numTryDecode]);
                    if (decodeResult.CorrectionSucceeded)
                    {
                        return(decodeResult.DecodedBytes);
                    }
                    arrayList.Add(decodeResult);
                    canvas.println("Decoding succeeded but could not correct");
                    canvas.println("all errors. Retrying..");
                }
                catch (DecodingFailedException ex)
                {
                    if (ex.Message.IndexOf("Finder Pattern") >= 0)
                    {
                        throw ex;
                    }
                }
                finally
                {
                    numTryDecode++;
                }
            }
            if (arrayList.Count == 0)
            {
                throw new DecodingFailedException("Give up decoding");
            }
            int num  = -1;
            int num2 = int.MaxValue;

            for (int i = 0; i < arrayList.Count; i++)
            {
                DecodeResult decodeResult = (DecodeResult)arrayList[i];
                if (decodeResult.NumErrors < num2)
                {
                    num2 = decodeResult.NumErrors;
                    num  = i;
                }
            }
            canvas.println("All trials need for correct error");
            canvas.println("Reporting #" + num + " that,");
            canvas.println("corrected minimum errors (" + num2 + ")");
            canvas.println("Decoding finished.");
            return(((DecodeResult)arrayList[num]).DecodedBytes);
        }
示例#14
0
    void Update()
    {
        DecodeResult result  = decoder.Result;
        bool         decoded = false;

        //Debug.Log("result" + result.Text);
        if (result.Success && resultString.text != result.Text)
        {
            resultString.text = result.Text;
            decoded           = true;
            Debug.Log(string.Format("Decoded: [{0}]{1}", result.BarcodeType, result.Text));
        }
    }
示例#15
0
        public async Task <DecodeResult> Process(DecodeMessageInfo info)
        {
            // Shortcuts have been taken.
            // Theoretically, it is possible that we receive an AS4Message that contains multiple
            // message-parts.  We should process each message-part seperately.

            using (var receivedStream = new MemoryStream(info.ReceivedMessage))
            {
                var as4Message = await RetrieveAS4Message(info.ContentType, receivedStream);

                if (as4Message == null)
                {
                    return(DecodeResult.CreateForBadRequest());
                }

                if (as4Message.IsSignalMessage)
                {
                    return(DecodeResult.CreateAccepted(as4Message.FirstSignalMessage is Receipt ? EbmsMessageType.Receipt : EbmsMessageType.Error,
                                                       as4Message.GetPrimaryMessageId(),
                                                       (as4Message.FirstSignalMessage as Error)));
                }

                // Start Processing
                var receivingPMode = await AssembleReceivingPMode(info);

                var respondingPMode = await AssembleRespondingPMode(info);

                if (receivingPMode == null)
                {
                    return(DecodeResult.CreateForBadRequest());
                }

                if (respondingPMode == null)
                {
                    return(DecodeResult.CreateForBadRequest());
                }

                var context = CreateMessagingContext(as4Message, receivingPMode, respondingPMode);

                try
                {
                    var decodeResult = await PerformInboundProcessing(context);

                    return(decodeResult);
                }
                finally
                {
                    context.Dispose();
                }
            }
        }
示例#16
0
        public DecodeResult PopResult(string id)
        {
            DecodeResult result  = null;
            bool         success = idToResult.TryRemove(id, out result);

            if (!success)
            {
                _logger.Error($"Strange to find ${id} not found in idToResult.");
                return(new DecodeResult {
                    Id = id, Message = "DecodingQueueIdNotFound"
                });
            }
            return(result);
        }
        private async Task LoadCanvas(int position)
        {
            // Skip other extensions
            var file = openFileParams.FileList[position];

            if (file.FileType != ".pbm" && file.FileType != ".pgm" && file.FileType != ".ppm")
            {
                return;
            }

            // Skip corrupted formats
            DecodeResult result = await anymapDecoder.decode(file);

            imagesInfo[position] = result;
            if (result.Bytes == null)
            {
                return;
            }

            Double width      = ApplicationView.GetForCurrentView().VisibleBounds.Width;
            Double height     = ApplicationView.GetForCurrentView().VisibleBounds.Height;
            Double widthDiff  = result.Width - width;
            Double heightDiff = result.Height - height;

            if (widthDiff > 0 || heightDiff > 0)
            {
                if (widthDiff > heightDiff)
                {
                    result.CurrentZoom = (Single)width / result.Width;
                }
                else
                {
                    result.CurrentZoom = (Single)height / result.Height;
                }
            }
            // Create canvas
            CanvasControl canvas = new CanvasControl()
            {
                Tag = result
            };

            canvas.CreateResources += Img_CreateResources;
            canvas.Draw            += Img_Draw;

            var wrapper = (FlipView.Items[position] as CanvasWrapper);

            wrapper.SetImageInfo(result);
            wrapper.Margin = new Thickness(0, 0, 0, 0);
            wrapper.SetCanvas(canvas);
        }
示例#18
0
        private static async Task <DecodeResult> PerformInboundProcessing(MessagingContext context)
        {
            var processingResult =
                await StepProcessor.ExecuteStepsAsync(context, StepRegistry.GetInboundProcessingConfiguration());

            if (processingResult.AS4Message == null)
            {
                throw new InvalidOperationException("An error occured while decoding the AS4 Message", processingResult.Exception);
            }

            if (processingResult.AS4Message.IsUserMessage)
            {
                try
                {
                    var deliverPayloads   = RetrievePayloadsFromMessage(processingResult.AS4Message);
                    var receivedMessageId = processingResult.EbmsMessageId;

                    var receiptResult =
                        await StepProcessor.ExecuteStepsAsync(processingResult, StepRegistry.GetReceiptCreationConfiguration());

                    if (receiptResult.AS4Message == null)
                    {
                        throw new InvalidOperationException("An unexpected error occured while creating the AS4 Receipt message", receiptResult.Exception);
                    }

                    return(DecodeResult.CreateWithReceipt(deliverPayloads.ToArray(),
                                                          Serializer.ToByteArray(receiptResult.AS4Message),
                                                          receivedMessageId,
                                                          receiptResult.AS4Message.GetPrimaryMessageId()));
                }
                finally
                {
                    processingResult.Dispose();
                }
            }

            if (!(processingResult.AS4Message.FirstSignalMessage is Error))
            {
                throw new InvalidProgramException("An AS4 Error Message was expected.");
            }

            // What we have now, must an error.
            return(DecodeResult.CreateWithError(Serializer.ToByteArray(processingResult.AS4Message),
                                                ((Error)processingResult.AS4Message.FirstSignalMessage),
                                                processingResult.AS4Message.FirstSignalMessage.RefToMessageId,
                                                processingResult.AS4Message.FirstSignalMessage.MessageId));
        }
示例#19
0
        public ActionResult Play(DecodedMessage msg)
        {
            var m = db.Messages.Where(ms => ms.Id == msg.MessageId).FirstOrDefault();

            DecodeResult dr = new DecodeResult();

            if (m != null)
            {
                double concordance = 0;
                if (!string.IsNullOrWhiteSpace(msg.OriginalMessage))
                {
                    concordance = m.Text.FuzzyCompare(msg.OriginalMessage);
                }
                dr.Fitness = concordance;
                dr.Score   = msg.Score;

                if (concordance > 0.85)
                {
                    dr.IsCorrect = true;
                }
                else
                {
                    dr.IsCorrect = false;
                }
            }
            else
            {
                dr.IsCorrect = false;
            }

            var login = MvcHelpers.GetUsername();
            var user  = db.Users.Where(a => a.Username == login).First();

            ViewBag.User     = login;
            user.Score       = (user.Score ?? 0) + (dr.IsCorrect ? msg.Score : -1);
            user.Complexity  = Math.Max(msg.Complexity, user.Complexity ?? 0) + (dr.IsCorrect ? 1 : 0);
            user.LastAttempt = DateTime.Now;
            user.Attempted   = (user.Attempted ?? 0) + 1;
            user.Deciphered  = (user.Deciphered ?? 0) + (dr.IsCorrect ? 1 : 0);
            db.SubmitChanges();

            dr.TotalScore = user.Score ?? 0;

            return(View("Result", dr));
        }
示例#20
0
        internal virtual DecodeResult decode(QRCodeImage qrCodeImage, Point adjust)
        {
            DecodeResult result;

            try
            {
                if (this.numTryDecode == 0)
                {
                    canvas.println("Decoding started");
                    int[][] image = this.imageToIntArray(qrCodeImage);
                    this.imageReader  = new QRCodeImageReader();
                    this.qrCodeSymbol = this.imageReader.getQRCodeSymbol(image);
                }
                else
                {
                    canvas.println("--");
                    canvas.println("Decoding restarted #" + this.numTryDecode);
                    this.qrCodeSymbol = this.imageReader.getQRCodeSymbolWithAdjustedGrid(adjust);
                }
            }
            catch (SymbolNotFoundException exception)
            {
                throw new DecodingFailedException(exception.Message);
            }
            canvas.println("Created QRCode symbol.");
            canvas.println("Reading symbol.");
            canvas.println("Version: " + this.qrCodeSymbol.VersionReference);
            canvas.println("Mask pattern: " + this.qrCodeSymbol.MaskPatternRefererAsString);
            int[] blocks = this.qrCodeSymbol.Blocks;
            canvas.println("Correcting data errors.");
            blocks = this.correctDataBlocks(blocks);
            try
            {
                sbyte[] decodedBytes = this.getDecodedByteArray(blocks, this.qrCodeSymbol.Version, this.qrCodeSymbol.NumErrorCollectionCode);
                result = new DecodeResult(this, decodedBytes, this.numLastCorrections, this.correctionSucceeded);
            }
            catch (InvalidDataBlockException exception2)
            {
                canvas.println(exception2.Message);
                throw new DecodingFailedException(exception2.Message);
            }
            return(result);
        }
示例#21
0
        private DecodeResult CallDecode(BitmapLuminanceSource imageAsLuminance, long singleStart)
        {
            var tempResults = new List <Result>();

            if (_config.TryMultipleBarcodeTypes)
            {
                tempResults = barcodeReader.DecodeMultiple(imageAsLuminance)?.ToList() ?? new List <Result>();
            }
            else
            {
                var result = barcodeReader.Decode(imageAsLuminance);
                tempResults.Add(result);
            }

            var mappedResult = new DecodeResult();

            if (tempResults.Count > 0)
            {
                mappedResult = new DecodeResult(tempResults[0]);
            }

            // search for the correct one (that works) if multiple results
            foreach (var item in tempResults)
            {
                if (item == null)
                {
                    continue;
                }

                var encodedData = StandardOutputTransformer.RetrieveNameAndPages(item.Text);
                if (!string.IsNullOrWhiteSpace(encodedData.Item1) && encodedData.Item2 != 0 && encodedData.Item3 != 0)
                {
                    mappedResult = new DecodeResult(item);
                    break;
                }
            }

            return(mappedResult);
        }
示例#22
0
 public static UInt16 DecodeThumb2(UInt16 inst1, UInt16 inst2, out DecodeResult type)
 {
     type = DecodeResult.INSTRUCTION_UNKNOWN;
     if ((inst1 & 0xF240) == 0xF240 && (~inst1 & 0x930) == 0x930 && !BitSet(inst2, 15))
     {
         uint data = 0;
         if (BitSet(inst1, 7))
         {
             type = DecodeResult.INSTRUCTION_MOVT;
         }
         else
         {
             type = DecodeResult.INSTRUCTION_MOVW;
         }
         data |= ((uint)inst2 & 0xFF);
         data |= ((uint)inst2 & 0x7000) >> 12 << 8;
         data |= ((uint)inst1 & 0x400) >> 10 << 11;
         data |= ((uint)inst1 & 0xF) << 12;
         return((UInt16)data);
     }
     return(0);
 }
示例#23
0
    /// <summary>
    /// Decode data. Save result in this.source
    /// </summary>
    /// <param name="inData"></param>
    /// <returns></returns>
    public void Decode(byte[] inData)
    {
        DecodeResult _result = RunDecodingScript(inData);

        if (_result == null)
        {
            return;
        }

        UnlockBits();

        if (this.Source != null)
        {
            this.Source.Dispose();
        }
        this.Source = new Bitmap(_result.width, _result.height);

        LockBits();

        Pixels = _result.pixels;

        UnlockBits(true);
    }
示例#24
0
        public void TestNonPeriodicBottomUp()
        {
            SetUp();
            builder.Name("day of week")
            .W(5)
            .N(14)
            .Radius(1.0)
            .MinVal(1.0)
            .MaxVal(10.0)
            .Periodic(false)
            .Forced(true);
            InitSe();

            Console.WriteLine(string.Format("Testing non-periodic encoder encoding resolution of {0}", se.GetResolution()));

            Assert.IsTrue(Arrays.AreEqual(se.Encode(1d), new[] { 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 }));
            Assert.IsTrue(Arrays.AreEqual(se.Encode(2d), new[] { 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0 }));
            Assert.IsTrue(Arrays.AreEqual(se.Encode(10d), new[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1 }));

            // Test that we get the same encoder when we construct it using resolution
            // instead of n
            SetUp();
            builder.Name("day of week")
            .W(5)
            .Radius(5.0)
            .MinVal(1.0)
            .MaxVal(10.0)
            .Periodic(false)
            .Forced(true);
            InitSe();

            double v = se.GetMinVal();

            while (v < se.GetMaxVal())
            {
                int[]        output         = se.Encode(v);
                DecodeResult decodedInWhile = (DecodeResult)se.Decode(output, "");
                Console.WriteLine("decoding " + Arrays.ToString(output) + string.Format("({0})=>", v) + se.DecodedToStr(decodedInWhile));

                Assert.AreEqual(decodedInWhile.GetFields().Count, 1, 0);
                List <RangeList> rangeListInWhile = new List <RangeList>(decodedInWhile.GetFields().Values);
                Assert.AreEqual(rangeListInWhile[0].Count, 1, 0);
                MinMax minMax = rangeListInWhile[0].GetRanges()[0];
                Assert.AreEqual(minMax.Min(), minMax.Max(), 0);
                Assert.IsTrue(Math.Abs(minMax.Min() - v) <= se.GetResolution());

                List <EncoderResult> topDowns = se.TopDownCompute(output);
                EncoderResult        topDown  = topDowns[0];
                Console.WriteLine("topDown => " + topDown);
                Assert.IsTrue(Arrays.AreEqual(topDown.GetEncoding(), output));
                Assert.IsTrue(Math.Abs(((double)topDown.GetValue()) - v) <= se.GetResolution());

                //Test bucket support
                int[] bucketIndices = se.GetBucketIndices(v);
                Console.WriteLine("bucket index => " + bucketIndices[0]);
                topDown = se.GetBucketInfo(bucketIndices)[0];
                Assert.IsTrue(Math.Abs(((double)topDown.GetValue()) - v) <= se.GetResolution() / 2);
                Assert.AreEqual(topDown.GetScalar(), (int)Convert.ChangeType(topDown.GetValue(), typeof(int)));
                Assert.IsTrue(Arrays.AreEqual(topDown.GetEncoding(), output));

                // Next value
                v += se.GetResolution() / 4;
            }

            // Make sure we can fill in holes
            DecodeResult decoded = (DecodeResult)se.Decode(new[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1 }, "");

            Assert.AreEqual(decoded.GetFields().Count, 1, 0);
            List <RangeList> rangeList = new List <RangeList>(decoded.GetFields().Values);

            Assert.AreEqual(1, rangeList[0].Count, 0);
            Console.WriteLine("decodedToStr of " + rangeList + " => " + se.DecodedToStr(decoded));

            decoded = (DecodeResult)se.Decode(new[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1 }, "");
            Assert.AreEqual(decoded.GetFields().Count, 1, 0);
            rangeList = new List <RangeList>(decoded.GetFields().Values);
            Assert.AreEqual(1, rangeList[0].Count, 0);
            Console.WriteLine("decodedToStr of " + rangeList + " => " + se.DecodedToStr(decoded));

            // Test min and max
            SetUp();
            builder.Name("scalar")
            .W(3)
            .MinVal(1.0)
            .MaxVal(10.0)
            .Periodic(false)
            .Forced(true);
            InitSe();

            List <EncoderResult> decode = se.TopDownCompute(new[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1 });

            Assert.AreEqual(10, (double)decode[0].GetScalar(), 0);
            decode = se.TopDownCompute(new[] { 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 });
            Assert.AreEqual(1, (double)decode[0].GetScalar(), 0);

            // Make sure only the last and first encoding encodes to max and min, and there is no value greater than max or min
            SetUp();
            builder.Name("scalar")
            .W(3)
            .N(140)
            .Radius(1.0)
            .MinVal(1.0)
            .MaxVal(141.0)
            .Periodic(false)
            .Forced(true);
            InitSe();

            List <int[]> iterlist = new List <int[]>();

            for (int i = 0; i < 137; i++)
            {
                iterlist.Add(new int[140]);
                ArrayUtils.SetRangeTo(iterlist[i], i, i + 3, 1);
                decode = se.TopDownCompute(iterlist[i]);
                int value = (int)decode[0].GetScalar();
                Assert.IsTrue(value <= 141);
                Assert.IsTrue(value >= 1);
                Assert.IsTrue(value < 141 || i == 137);
                Assert.IsTrue(value > 1 || i == 0);
            }

            // -------------------------------------------------------------------------
            // Test the input description generation and top-down compute on a small number
            //   non-periodic encoder
            SetUp();
            builder.Name("scalar")
            .W(3)
            .N(15)
            .MinVal(.001)
            .MaxVal(.002)
            .Periodic(false)
            .Forced(true);
            InitSe();

            Console.WriteLine(string.Format("\nTesting non-periodic encoder decoding resolution of {0}...", se.GetResolution()));
            v = se.GetMinVal();
            while (v < se.GetMaxVal())
            {
                int[] output = se.Encode(v);
                decoded = (DecodeResult)se.Decode(output, "");
                Console.WriteLine(string.Format("decoding ({0})=>", v) + " " + se.DecodedToStr(decoded));

                Assert.AreEqual(decoded.GetFields().Count, 1, 0);
                rangeList = new List <RangeList>(decoded.GetFields().Values);
                Assert.AreEqual(rangeList[0].Count, 1, 0);
                MinMax minMax = rangeList[0].GetRanges()[0];
                Assert.AreEqual(minMax.Min(), minMax.Max(), 0);
                Assert.IsTrue(Math.Abs(minMax.Min() - v) <= se.GetResolution());

                decode = se.TopDownCompute(output);
                Console.WriteLine("topdown => " + Arrays.ToString(decode.ToArray()));
                Console.WriteLine("{0} <= {1}", Math.Abs(decode[0].GetScalar() - v), se.GetResolution() / 2);
                Assert.IsTrue(Math.Abs(decode[0].GetScalar() - v) <= se.GetResolution() / 2);

                v += (se.GetResolution() / 4);
            }

            // -------------------------------------------------------------------------
            // Test the input description generation on a large number, non-periodic encoder
            SetUp();
            builder.Name("scalar")
            .W(3)
            .N(15)
            .MinVal(1.0)
            .MaxVal(1000000000.0)
            .Periodic(false)
            .Forced(true);
            InitSe();

            Console.WriteLine(string.Format("\nTesting non-periodic encoder decoding resolution of {0}...", se.GetResolution()));
            v = se.GetMinVal();
            while (v < se.GetMaxVal())
            {
                int[] output = se.Encode(v);
                decoded = (DecodeResult)se.Decode(output, "");
                Console.WriteLine(string.Format("decoding ({0})=>", v) + " " + se.DecodedToStr(decoded));

                Assert.AreEqual(decoded.GetFields().Count, 1, 0);
                rangeList = new List <RangeList>(decoded.GetFields().Values);
                Assert.AreEqual(rangeList[0].Count, 1, 0);
                MinMax minMax = rangeList[0].GetRanges()[0];
                Assert.AreEqual(minMax.Min(), minMax.Max(), 0);
                Assert.IsTrue(Math.Abs(minMax.Min() - v) <= se.GetResolution());

                decode = se.TopDownCompute(output);
                Console.WriteLine("topdown => " + decode);
                Assert.IsTrue(Math.Abs(decode[0].GetScalar() - v) <= se.GetResolution() / 2);

                v += (se.GetResolution() / 4);
            }
        }
示例#25
0
 public static UInt32 DecodeARM32(UInt32 cur_inst, out DecodeResult type)
 {
     // if this doesn't change, error
     type = DecodeResult.INSTRUCTION_UNKNOWN;
     // Bits 31-28 should be 1110, Always Execute
     if (!(BitSet(cur_inst, 31) && BitSet(cur_inst, 30) && BitSet(cur_inst, 29) && !BitSet(cur_inst, 28)))
     {
         // Unsupported conditional instruction.
         return 0;
     }
     // Bits 27-25 should be 110 for supervisor calls
     if (BitSet(cur_inst, 27))
     {
         // Bit 24 should be set for SWI calls
         if (BitSet(cur_inst, 26) && BitSet(cur_inst, 25) && BitSet(cur_inst, 24))
         {
             type = DecodeResult.INSTRUCTION_SYSCALL;
             // TODO: Return syscall immediate value.
             return 1;
         }
     }
     // Bits 27-25 should be 001 for data instructions
     else if (!BitSet(cur_inst, 26) && BitSet(cur_inst, 25))
     {
         // Bits 24-23 should be 10
         if (!(BitSet(cur_inst, 24) && !BitSet(cur_inst, 23)))
         {
             // Not an valid ARM MOV instruction.
             return 0;
         }
         // Bits 21-20 should be 00
         if (!(!BitSet(cur_inst, 21) && !BitSet(cur_inst, 20)))
         {
             // Invalid ARM MOV instruction.
             return 0;
         }
         // Bit 22 is 1 for top load 0 for bottom load
         if (BitSet(cur_inst, 22)) // top load
         {
             type = DecodeResult.INSTRUCTION_MOVT;
         }
         else
         {
             type = DecodeResult.INSTRUCTION_MOVW;
         }
         // Immediate value at 19-16 and 11-0
         // discard bytes 31-20
         // discard bytes 15-0
         return (((cur_inst << 12) >> 28) << 12) | ((cur_inst << 20) >> 20);
     }
     // Bits 27-25 should be 000 for jump instructions
     else if (!BitSet(cur_inst, 26) && !BitSet(cur_inst, 25))
     {
         // Bits 24-4 should be 100101111111111110001, 0x12FFF1 for BX
         if ((cur_inst << 7) >> 11 == 0x12FFF1)
         {
             type = DecodeResult.INSTRUCTION_BRANCH;
             return 0;
         }
         // Bits 24-4 should be 100101111111111110011, 0x12FFF3 for BLX
         else if ((cur_inst << 7) >> 11 == 0x12FFF3)
         {
             type = DecodeResult.INSTRUCTION_BRANCH;
             return 0;
         }
         else
         {
             // unknown jump
             return 0;
         }
     }
     else
     {
         // Unsupported instruction.
         return 0;
     }
     return 0;
 }
示例#26
0
 internal virtual DecodeResult decode(QRCodeImage qrCodeImage, Point adjust)
 {
     DecodeResult result;
     try
     {
         if (this.numTryDecode == 0)
         {
             canvas.println("Decoding started");
             int[][] image = this.imageToIntArray(qrCodeImage);
             this.imageReader = new QRCodeImageReader();
             this.qrCodeSymbol = this.imageReader.getQRCodeSymbol(image);
         }
         else
         {
             canvas.println("--");
             canvas.println("Decoding restarted #" + this.numTryDecode);
             this.qrCodeSymbol = this.imageReader.getQRCodeSymbolWithAdjustedGrid(adjust);
         }
     }
     catch (SymbolNotFoundException exception)
     {
         throw new DecodingFailedException(exception.Message);
     }
     canvas.println("Created QRCode symbol.");
     canvas.println("Reading symbol.");
     canvas.println("Version: " + this.qrCodeSymbol.VersionReference);
     canvas.println("Mask pattern: " + this.qrCodeSymbol.MaskPatternRefererAsString);
     int[] blocks = this.qrCodeSymbol.Blocks;
     canvas.println("Correcting data errors.");
     blocks = this.correctDataBlocks(blocks);
     try
     {
         sbyte[] decodedBytes = this.getDecodedByteArray(blocks, this.qrCodeSymbol.Version, this.qrCodeSymbol.NumErrorCollectionCode);
         result = new DecodeResult(this, decodedBytes, this.numLastCorrections, this.correctionSucceeded);
     }
     catch (InvalidDataBlockException exception2)
     {
         canvas.println(exception2.Message);
         throw new DecodingFailedException(exception2.Message);
     }
     return result;
 }
 public CanvasWrapper(DecodeResult imageInfo)
 {
     SetImageInfo(imageInfo);
 }
示例#28
0
        public void TestDecodeAndResolution()
        {
            SetUp();
            builder.Name("scalar");
            InitSe();
            double        resolution = se.GetResolution();
            StringBuilder @out       = new StringBuilder();

            for (double v = se.GetMinVal(); v < se.GetMaxVal(); v += (resolution / 4.0d))
            {
                int[]        output       = se.Encode(v);
                DecodeResult decodedInFor = (DecodeResult)se.Decode(output, "");

                Console.WriteLine(@out.Append("decoding ").Append(Arrays.ToString(output)).Append(" (").
                                  Append(string.Format("{0}", v)).Append(")=> ").Append(se.DecodedToStr(decodedInFor)));
                @out.Length = 0;

                Map <string, RangeList> fieldsMapInFor = decodedInFor.GetFields();
                Assert.AreEqual(1, fieldsMapInFor.Count);
                RangeList ranges = new List <RangeList>(fieldsMapInFor.Values)[0];
                Assert.AreEqual(1, ranges.Count);
                Assert.AreEqual(ranges.GetRange(0).Min(), ranges.GetRange(0).Max(), 0);
                Assert.IsTrue(ranges.GetRange(0).Min() - v < se.GetResolution());

                EncoderResult topDown = se.TopDownCompute(output)[0];
                Console.WriteLine("topdown => " + topDown);
                Assert.IsTrue(Arrays.AreEqual(topDown.GetEncoding(), output));
                Assert.IsTrue(Math.Abs(((double)topDown.Get(1)) - v) <= se.GetResolution() / 2);

                //Test bucket support
                int[] bucketIndices = se.GetBucketIndices(v);
                Console.WriteLine("bucket index => " + bucketIndices[0]);
                topDown = se.GetBucketInfo(bucketIndices)[0];
                Assert.IsTrue(Math.Abs(((double)topDown.Get(1)) - v) <= se.GetResolution() / 2);
                Assert.AreEqual(topDown.Get(1), se.GetBucketValues <double>(typeof(double)).ToArray()[bucketIndices[0]]);

                Assert.AreEqual(topDown.Get(2), topDown.Get(1));

                Assert.IsTrue(Arrays.AreEqual(topDown.GetEncoding(), output));
            }

            // -----------------------------------------------------------------------
            // Test the input description generation on a large number, periodic encoder
            SetUp();
            builder.Name("scalar")
            .W(3)
            .Radius(1.5)
            .MinVal(1.0)
            .MaxVal(8.0)
            .Periodic(true)
            .Forced(true);

            InitSe();

            Console.WriteLine("\nTesting periodic encoder decoding, resolution of " + se.GetResolution());

            //Test with a "hole"
            int[]                   encoded   = new[] { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 };
            DecodeResult            decoded   = (DecodeResult)se.Decode(encoded, "");
            Map <string, RangeList> fieldsMap = decoded.GetFields();

            Assert.AreEqual(1, fieldsMap.Count);
            Assert.AreEqual(1, decoded.GetRanges("scalar").Count);
            Assert.AreEqual("7.5, 7.5", decoded.GetRanges("scalar").GetRange(0).ToString());

            //Test with something wider than w, and with a hole, and wrapped
            encoded   = new[] { 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 };
            decoded   = (DecodeResult)se.Decode(encoded, "");
            fieldsMap = decoded.GetFields();

            Assert.AreEqual(1, fieldsMap.Count);
            Assert.AreEqual(2, decoded.GetRanges("scalar").Count);
            Assert.AreEqual("7.5, 8.0", decoded.GetRanges("scalar").GetRange(0).ToString());

            //Test with something wider than w, no hole
            encoded   = new[] { 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
            decoded   = (DecodeResult)se.Decode(encoded, "");
            fieldsMap = decoded.GetFields();

            Assert.AreEqual(1, fieldsMap.Count);
            Assert.AreEqual(1, decoded.GetRanges("scalar").Count);
            Assert.AreEqual(decoded.GetRanges("scalar").GetRange(0).ToString(), "1.5, 2.5");

            //Test with 2 ranges
            encoded   = new[] { 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0 };
            decoded   = (DecodeResult)se.Decode(encoded, "");
            fieldsMap = decoded.GetFields();

            Assert.AreEqual(1, fieldsMap.Count);
            Assert.AreEqual(2, decoded.GetRanges("scalar").Count);
            Assert.AreEqual(decoded.GetRanges("scalar").GetRange(0).ToString(), "1.5, 1.5");
            Assert.AreEqual(decoded.GetRanges("scalar").GetRange(1).ToString(), "5.5, 6.0");

            //Test with 2 ranges, 1 of which is narrower than w
            encoded   = new[] { 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0 };
            decoded   = (DecodeResult)se.Decode(encoded, "");
            fieldsMap = decoded.GetFields();

            Assert.AreEqual(1, fieldsMap.Count);
            Assert.AreEqual(2, decoded.GetRanges("scalar").Count);
            Assert.AreEqual(decoded.GetRanges("scalar").GetRange(0).ToString(), "1.5, 1.5");
            Assert.AreEqual(decoded.GetRanges("scalar").GetRange(1).ToString(), "5.5, 6.0");
        }
        private async Task <DecodeResult> decode(IRandomAccessStream stream, String filename)
        {
            ulong        size   = stream.Size;
            DecodeResult result = new DecodeResult();

            result.Type        = 0;
            result.Width       = 0;
            result.Height      = 0;
            result.Bytes       = null;
            result.Filename    = filename;
            result.CurrentZoom = 1.0f;
            if (size >= 2)
            {
                stream.Seek(0);
                var dataReader = new DataReader(stream);
                await dataReader.LoadAsync((uint)2);

                string formatType = dataReader.ReadString(2);
                if (formatType[0] != 'P')
                {
                    return(result);
                }
                AnymapProperties properties      = null;
                byte[]           decodedAnymap   = null;
                uint             bytesLoaded     = 0;
                uint             pixelsNum       = 0;
                uint             packedPixelsNum = 0;
                switch (formatType[1])
                {
                case '1':
                    properties = await GetImageProperties(stream, false);

                    if (properties.MaxValue != 0)
                    {
                        decodedAnymap = new byte[properties.Width * properties.Height * 4];
                        stream.Seek(properties.StreamPosition);
                        dataReader  = new DataReader(stream);
                        bytesLoaded = await dataReader.LoadAsync((uint)(stream.Size - properties.StreamPosition));

                        String strAll = dataReader.ReadString(bytesLoaded);
                        if (properties.BytesPerColor == 1)
                        {
                            int             resultIndex = 0;
                            String[]        strs        = strAll.Split(new String[] { "\r", "\r\n", "\n" }, StringSplitOptions.None);
                            MatchCollection mc          = null;
                            foreach (string str in strs)
                            {
                                mc = Regex.Matches(Regex.Match(str, @"[^#]{0,}").ToString(), @"\b\d+");
                                for (int i = 0; i < mc.Count && resultIndex < decodedAnymap.Length; ++i)
                                {
                                    decodedAnymap[resultIndex]     = (byte)((Convert.ToUInt32(mc[i].Value) ^ 0x01) * 255);
                                    decodedAnymap[resultIndex + 1] = decodedAnymap[resultIndex];
                                    decodedAnymap[resultIndex + 2] = decodedAnymap[resultIndex];
                                    decodedAnymap[resultIndex + 3] = 255;
                                    resultIndex += 4;
                                }
                            }
                        }
                    }
                    result.Type   = 1;
                    result.Width  = (Int32)properties.Width;
                    result.Height = (Int32)properties.Height;
                    result.Bytes  = decodedAnymap;
                    result.DoubleBytesPerColor = properties.BytesPerColor == 2;
                    break;

                case '2':
                    properties = await GetImageProperties(stream, true);

                    if (properties.MaxValue != 0)
                    {
                        stream.Seek(properties.StreamPosition);
                        dataReader  = new DataReader(stream);
                        bytesLoaded = await dataReader.LoadAsync((uint)(stream.Size - properties.StreamPosition));

                        String strAll = dataReader.ReadString(bytesLoaded);
                        if (properties.BytesPerColor == 1)
                        {
                            decodedAnymap = new byte[properties.Width * properties.Height * 4];
                            int             resultIndex = 0;
                            String[]        strs        = strAll.Split(new String[] { "\r", "\r\n", "\n" }, StringSplitOptions.None);
                            MatchCollection mc          = null;
                            foreach (string str in strs)
                            {
                                mc = Regex.Matches(Regex.Match(str, @"[^#]{0,}").ToString(), @"\b\d+");
                                for (int i = 0; i < mc.Count && resultIndex < decodedAnymap.Length; ++i)
                                {
                                    decodedAnymap[resultIndex]     = (byte)(Convert.ToUInt32(mc[i].Value) / (double)properties.MaxValue * 255);
                                    decodedAnymap[resultIndex + 1] = decodedAnymap[resultIndex];
                                    decodedAnymap[resultIndex + 2] = decodedAnymap[resultIndex];
                                    decodedAnymap[resultIndex + 3] = 255;
                                    resultIndex += 4;
                                }
                            }
                        }
                        else
                        {
                            decodedAnymap = new byte[properties.Width * properties.Height * 8];
                            int             resultIndex = 0;
                            String[]        strs        = strAll.Split(new String[] { "\r", "\r\n", "\n" }, StringSplitOptions.None);
                            MatchCollection mc          = null;
                            UInt16          tmp         = 0;
                            foreach (string str in strs)
                            {
                                mc = Regex.Matches(Regex.Match(str, @"[^#]{0,}").ToString(), @"\b\d+");
                                for (int i = 0; i < mc.Count && resultIndex < decodedAnymap.Length; ++i)
                                {
                                    tmp = (UInt16)(Convert.ToUInt32(mc[i].Value) / (double)properties.MaxValue * 65535);
                                    decodedAnymap[resultIndex + 1] = (byte)(tmp >> 8);
                                    decodedAnymap[resultIndex]     = (byte)(tmp & 0x00FF);

                                    decodedAnymap[resultIndex + 3] = decodedAnymap[resultIndex + 1];
                                    decodedAnymap[resultIndex + 2] = decodedAnymap[resultIndex];

                                    decodedAnymap[resultIndex + 5] = decodedAnymap[resultIndex + 1];
                                    decodedAnymap[resultIndex + 4] = decodedAnymap[resultIndex];

                                    decodedAnymap[resultIndex + 7] = 255;
                                    decodedAnymap[resultIndex + 6] = 255;
                                    resultIndex += 8;
                                }
                            }
                        }
                    }
                    result.Type   = 2;
                    result.Width  = (Int32)properties.Width;
                    result.Height = (Int32)properties.Height;
                    result.Bytes  = decodedAnymap;
                    result.DoubleBytesPerColor = properties.BytesPerColor == 2;
                    break;

                case '3':
                    result.HistogramValues = new List <List <HistogramValue> >(3);
                    result.HistogramValues.Add(new List <HistogramValue>(256));
                    result.HistogramValues.Add(new List <HistogramValue>(256));
                    result.HistogramValues.Add(new List <HistogramValue>(256));
                    foreach (List <HistogramValue> list in result.HistogramValues)
                    {
                        for (int i = 0; i < 256; ++i)
                        {
                            list.Add(new HistogramValue {
                                Brightness = i, Level = 0.0
                            });
                        }
                    }
                    properties = await GetImageProperties(stream, true);

                    if (properties.MaxValue != 0)
                    {
                        stream.Seek(properties.StreamPosition);
                        dataReader  = new DataReader(stream);
                        bytesLoaded = await dataReader.LoadAsync((uint)(stream.Size - properties.StreamPosition));

                        String strAll = dataReader.ReadString(bytesLoaded);
                        if (properties.BytesPerColor == 1)
                        {
                            decodedAnymap = new byte[properties.Width * properties.Height * 4];
                            int             resultIndex = 0;
                            string[]        strs        = strAll.Split(new String[] { "\r", "\r\n", "\n" }, StringSplitOptions.None);
                            int             BgraIndex   = 2;
                            MatchCollection mc          = null;
                            foreach (string str in strs)
                            {
                                mc = Regex.Matches(Regex.Match(str, @"[^#]{0,}").ToString(), @"\b\d+");
                                for (int i = 0; i < mc.Count; ++i)
                                {
                                    decodedAnymap[resultIndex + BgraIndex] = (byte)(Convert.ToUInt32(mc[i].Value) / (double)properties.MaxValue * 255);
                                    result.HistogramValues[BgraIndex][decodedAnymap[resultIndex + BgraIndex]].Level += 1.0;
                                    --BgraIndex;
                                    if (BgraIndex == -1)
                                    {
                                        BgraIndex = 3;
                                        decodedAnymap[resultIndex + BgraIndex] = 255;
                                        resultIndex += 4;
                                        --BgraIndex;
                                        if (resultIndex >= decodedAnymap.Length)
                                        {
                                            break;
                                        }
                                    }
                                }
                                if (resultIndex >= decodedAnymap.Length)
                                {
                                    break;
                                }
                            }
                        }
                        else
                        {
                            decodedAnymap = new byte[properties.Width * properties.Height * 8];
                            int             resultIndex = 0;
                            string[]        strs        = strAll.Split(new String[] { "\r", "\r\n", "\n" }, StringSplitOptions.None);
                            MatchCollection mc          = null;
                            UInt16          tmp         = 0;
                            int             rgbaIndex   = 0;
                            foreach (string str in strs)
                            {
                                mc = Regex.Matches(Regex.Match(str, @"[^#]{0,}").ToString(), @"\b\d+");
                                for (int i = 0; i < mc.Count; ++i)
                                {
                                    tmp = (UInt16)(Convert.ToUInt32(mc[i].Value) / (double)properties.MaxValue * 65535);
                                    decodedAnymap[resultIndex + rgbaIndex + 1] = (byte)(tmp >> 8);
                                    decodedAnymap[resultIndex + rgbaIndex + 0] = (byte)(tmp & 0x00FF);
                                    rgbaIndex += 2;
                                    if (rgbaIndex == 6)
                                    {
                                        decodedAnymap[resultIndex + 7] = 255;
                                        decodedAnymap[resultIndex + 6] = 255;
                                        rgbaIndex    = 0;
                                        resultIndex += 8;
                                    }
                                }
                                if (resultIndex >= decodedAnymap.Length)
                                {
                                    break;
                                }
                            }
                        }
                    }
                    result.Type   = 3;
                    result.Width  = (Int32)properties.Width;
                    result.Height = (Int32)properties.Height;
                    result.Bytes  = decodedAnymap;
                    result.DoubleBytesPerColor = properties.BytesPerColor == 2;
                    break;

                case '4':
                    properties = await GetImageProperties(stream, false);

                    pixelsNum     = properties.Width * properties.Height;
                    decodedAnymap = new byte[pixelsNum * 4];
                    stream.Seek(properties.StreamPosition);
                    dataReader  = new DataReader(stream);
                    bytesLoaded = await dataReader.LoadAsync((uint)(stream.Size - properties.StreamPosition));

                    if (properties.BytesPerColor == 1)
                    {
                        int resultIndex = 0;
                        int mod         = (int)(properties.Width * properties.Height) % 8;
                        int colmod      = (int)(properties.Width) % 8;
                        packedPixelsNum = (properties.Width / 8 + (uint)(colmod == 0 ? 0 : 1)) * properties.Height;
                        uint col = 0;
                        int  num = 0;
                        for (uint i = 0; i < packedPixelsNum; ++i)
                        {
                            if (col == properties.Width - colmod)
                            {
                                num = colmod == 0 ? 8 : colmod;

                                unpackBitsPbm(decodedAnymap, resultIndex, num, dataReader.ReadByte());
                                col          = 0;
                                resultIndex += num * 4;
                            }
                            else
                            {
                                unpackBitsPbm(decodedAnymap, resultIndex, 8, dataReader.ReadByte());
                                col         += 8;
                                resultIndex += 32;
                            }
                        }
                    }
                    result.Type   = 4;
                    result.Width  = (Int32)properties.Width;
                    result.Height = (Int32)properties.Height;
                    result.Bytes  = decodedAnymap;
                    result.DoubleBytesPerColor = properties.BytesPerColor == 2;
                    break;

                case '5':
                    properties = await GetImageProperties(stream, true);

                    if (properties.MaxValue != 0)
                    {
                        stream.Seek(properties.StreamPosition);
                        dataReader  = new DataReader(stream);
                        bytesLoaded = await dataReader.LoadAsync((uint)(stream.Size - properties.StreamPosition));

                        if (properties.BytesPerColor == 1)
                        {
                            decodedAnymap = new byte[properties.Width * properties.Height * 4];
                            uint resultIndex = 0;
                            for (int i = 0; i < properties.Height; ++i)
                            {
                                for (int j = 0; j < properties.Width && dataReader.UnconsumedBufferLength >= 1; ++j)
                                {
                                    decodedAnymap[resultIndex]     = (byte)(dataReader.ReadByte() / (double)properties.MaxValue * 255);
                                    decodedAnymap[resultIndex + 1] = decodedAnymap[resultIndex];
                                    decodedAnymap[resultIndex + 2] = decodedAnymap[resultIndex];
                                    decodedAnymap[resultIndex + 3] = 255;
                                    resultIndex += 4;
                                }
                            }
                        }
                        else
                        {
                            decodedAnymap = new byte[properties.Width * properties.Height * 8];
                            uint   resultIndex = 0;
                            UInt16 tmp;
                            for (int i = 0; i < properties.Height; ++i)
                            {
                                for (int j = 0; j < properties.Width && dataReader.UnconsumedBufferLength >= 1; ++j)
                                {
                                    tmp   = dataReader.ReadByte();
                                    tmp <<= 8;
                                    tmp  += dataReader.ReadByte();
                                    tmp   = (UInt16)(tmp / (Double)properties.MaxValue * 65535);
                                    decodedAnymap[resultIndex + 1] = (byte)(tmp >> 8);
                                    decodedAnymap[resultIndex]     = (byte)(tmp & 0x00FF);

                                    decodedAnymap[resultIndex + 3] = decodedAnymap[resultIndex + 1];
                                    decodedAnymap[resultIndex + 2] = decodedAnymap[resultIndex];

                                    decodedAnymap[resultIndex + 5] = decodedAnymap[resultIndex + 1];
                                    decodedAnymap[resultIndex + 4] = decodedAnymap[resultIndex];

                                    decodedAnymap[resultIndex + 7] = 255;
                                    decodedAnymap[resultIndex + 6] = 255;
                                    resultIndex += 8;
                                }
                            }
                        }
                    }
                    result.Type   = 5;
                    result.Width  = (Int32)properties.Width;
                    result.Height = (Int32)properties.Height;
                    result.Bytes  = decodedAnymap;
                    result.DoubleBytesPerColor = properties.BytesPerColor == 2;
                    break;

                case '6':
                    result.HistogramValues = new List <List <HistogramValue> >(3);
                    result.HistogramValues.Add(new List <HistogramValue>(256));
                    result.HistogramValues.Add(new List <HistogramValue>(256));
                    result.HistogramValues.Add(new List <HistogramValue>(256));
                    foreach (List <HistogramValue> list in result.HistogramValues)
                    {
                        for (int i = 0; i < 256; ++i)
                        {
                            list.Add(new HistogramValue {
                                Brightness = i, Level = 0.0
                            });
                        }
                    }
                    properties = await GetImageProperties(stream, true);

                    if (properties.MaxValue != 0)
                    {
                        decodedAnymap = new byte[properties.Width * properties.Height * 4];
                        stream.Seek(properties.StreamPosition);
                        dataReader = new DataReader(stream);

                        bytesLoaded = await dataReader.LoadAsync((uint)(stream.Size - properties.StreamPosition));

                        if (properties.BytesPerColor == 1)
                        {
                            uint resultIndex = 0;
                            for (int i = 0; i < properties.Height; ++i)
                            {
                                for (int j = 0; j < properties.Width && dataReader.UnconsumedBufferLength >= 3; ++j)
                                {
                                    decodedAnymap[resultIndex + 2] = (byte)(dataReader.ReadByte() / (double)properties.MaxValue * 255);
                                    decodedAnymap[resultIndex + 1] = (byte)(dataReader.ReadByte() / (double)properties.MaxValue * 255);
                                    decodedAnymap[resultIndex]     = (byte)(dataReader.ReadByte() / (double)properties.MaxValue * 255);
                                    decodedAnymap[resultIndex + 3] = 255;
                                    result.HistogramValues[0][decodedAnymap[resultIndex + 2]].Level += 1.0;
                                    result.HistogramValues[1][decodedAnymap[resultIndex + 1]].Level += 1.0;
                                    result.HistogramValues[2][decodedAnymap[resultIndex]].Level     += 1.0;
                                    resultIndex += 4;
                                }
                            }
                        }
                        else
                        {
                            decodedAnymap = new byte[properties.Width * properties.Height * 8];
                            uint   resultIndex = 0;
                            UInt16 tmp;
                            for (int i = 0; i < properties.Height; ++i)
                            {
                                for (int j = 0; j < properties.Width && dataReader.UnconsumedBufferLength >= 1; ++j)
                                {
                                    tmp   = dataReader.ReadByte();
                                    tmp <<= 8;
                                    tmp  += dataReader.ReadByte();
                                    tmp   = (UInt16)(tmp / (Double)properties.MaxValue * 65535);
                                    decodedAnymap[resultIndex + 1] = (byte)(tmp >> 8);
                                    decodedAnymap[resultIndex]     = (byte)(tmp & 0x00FF);

                                    tmp   = dataReader.ReadByte();
                                    tmp <<= 8;
                                    tmp  += dataReader.ReadByte();
                                    tmp   = (UInt16)(tmp / (Double)properties.MaxValue * 65535);
                                    decodedAnymap[resultIndex + 3] = (byte)(tmp >> 8);
                                    decodedAnymap[resultIndex + 2] = (byte)(tmp & 0x00FF);

                                    tmp   = dataReader.ReadByte();
                                    tmp <<= 8;
                                    tmp  += dataReader.ReadByte();
                                    tmp   = (UInt16)(tmp / (Double)properties.MaxValue * 65535);
                                    decodedAnymap[resultIndex + 5] = (byte)(tmp >> 8);
                                    decodedAnymap[resultIndex + 4] = (byte)(tmp & 0x00FF);

                                    decodedAnymap[resultIndex + 7] = 255;
                                    decodedAnymap[resultIndex + 6] = 255;
                                    resultIndex += 8;
                                }
                            }
                        }
                    }
                    result.Type   = 6;
                    result.Width  = (Int32)properties.Width;
                    result.Height = (Int32)properties.Height;
                    result.Bytes  = decodedAnymap;
                    result.DoubleBytesPerColor = properties.BytesPerColor == 2;
                    break;
                }
                dataReader.DetachBuffer();
                dataReader.DetachStream();
                dataReader.Dispose();
            }
            //foreach (List<HistogramValue> list in result.HistogramValues)
            //{
            //    foreach (HistogramValue value in list)
            //    {
            //        value.Level /= result.Width * result.Height;
            //    }
            //}
            GC.Collect();
            return(result);
        }
示例#30
0
 public static UInt16 DecodeThumb2(UInt16 inst1, UInt16 inst2, out DecodeResult type)
 {
     type = DecodeResult.INSTRUCTION_UNKNOWN;
     if ((inst1 & 0xF240) == 0xF240 && (~inst1 & 0x930) == 0x930 && !BitSet(inst2, 15))
     {
         uint data = 0;
         if (BitSet(inst1, 7))
         {
             type = DecodeResult.INSTRUCTION_MOVT;
         }
         else
         {
             type = DecodeResult.INSTRUCTION_MOVW;
         }
         data |= ((uint)inst2 & 0xFF);
         data |= ((uint)inst2 & 0x7000) >> 12 << 8;
         data |= ((uint)inst1 & 0x400) >> 10 << 11;
         data |= ((uint)inst1 & 0xF) << 12;
         return (UInt16)data;
     }
     return 0;
 }
示例#31
0
        async Task <Mesh> ConvertDracoMeshToUnity(
            IntPtr encodedData,
            int size,
            bool requireNormals,
            bool requireTangents,
            int weightsAttributeId = -1,
            int jointsAttributeId  = -1,
            bool forceUnityLayout  = false
#if UNITY_EDITOR
            , bool sync = false
#endif
            )
#endif
        {
#if DRACO_MESH_DATA
            var dracoNative = new DracoNative(mesh, convertSpace);
            var result      = new DecodeResult();
#else
            var dracoNative = new DracoNative(convertSpace);
#endif

#if UNITY_EDITOR
            if (sync)
            {
                dracoNative.InitSync(encodedData, size);
            }
            else
#endif
            {
                await WaitForJobHandle(dracoNative.Init(encodedData, size));
            }
            if (dracoNative.ErrorOccured())
            {
#if DRACO_MESH_DATA
                return(result);
#else
                return(null);
#endif
            }
            if (!requireNormals && requireTangents)
            {
                // Sanity check: We need normals to calculate tangents
                requireNormals = true;
            }
#if DRACO_MESH_DATA
            dracoNative.CreateMesh(
                out result.calculateNormals,
                requireNormals,
                requireTangents,
                weightsAttributeId,
                jointsAttributeId,
                forceUnityLayout
                );
#else
            dracoNative.CreateMesh(
                out var calculateNormals,
                requireNormals,
                requireTangents,
                weightsAttributeId,
                jointsAttributeId,
                forceUnityLayout
                );
#endif

#if UNITY_EDITOR
            if (sync)
            {
                dracoNative.DecodeVertexDataSync();
            }
            else
#endif
            {
                await WaitForJobHandle(dracoNative.DecodeVertexData());
            }
            var error = dracoNative.ErrorOccured();
            dracoNative.DisposeDracoMesh();
            if (error)
            {
#if DRACO_MESH_DATA
                return(result);
#else
                return(null);
#endif
            }

#if !DRACO_MESH_DATA
            var result = dracoNative.PopulateMeshData();
            if (result.GetTopology(0) == MeshTopology.Triangles)
            {
                if (calculateNormals)
                {
                    // TODO: Consider doing this in a threaded Job
                    Profiler.BeginSample("RecalculateNormals");
                    result.RecalculateNormals();
                    Profiler.EndSample();
                }
                if (requireTangents)
                {
                    // TODO: Consider doing this in a threaded Job
                    Profiler.BeginSample("RecalculateTangents");
                    result.RecalculateTangents();
                    Profiler.EndSample();
                }
            }
#else
            result.success = dracoNative.PopulateMeshData();
            if (result.success && dracoNative.hasBoneWeightData)
            {
                result.boneWeightData = new BoneWeightData(dracoNative.bonesPerVertex, dracoNative.boneWeights);
                dracoNative.DisposeBoneWeightData();
            }
#endif
            return(result);
        }
示例#32
0
        public void Decoding(byte[] data)
        {
            char[]       endbuf = new char[2];
            DecodeResult result = DecodeResult.COMMAND_OK;
            string       key    = null;
            string       value  = null;

            pool.Append(data);

            if (pool.Length < 2)
            {
                return;
            }

            pool.CopyTo(pool.Length - 2, endbuf, 0, 2);

            if (endbuf[0] == '\r' && endbuf[1] == '\n')
            {
                if (pool.ToString().StartsWith(CommandHead) == false)
                {
                    pool.Clear();
                    CommandFinishHandler(DecodeResult.COMMAND_ERR_FORMAT, key, value);
                    return;
                }

                string[] strings = pool.ToString().Split(new string[] { CommandConnect }, StringSplitOptions.None);
                pool.Clear();
                if (strings == null || strings.Length == 0 || strings[0].Trim().CompareTo(CommandHead) != 0)
                {
                    result = DecodeResult.COMMAND_ERR_FORMAT;
                }
                else if (strings.Length == 1)
                {
                    result = DecodeResult.COMMAND_NOP;
                }
                else
                {
                    string[] keyValue = strings[1].Split(new string[] { CommandSplit }, StringSplitOptions.RemoveEmptyEntries);

                    key = keyValue[0].Trim();
                    if (key.Length == 0)
                    {
                        key    = null;
                        result = DecodeResult.COMMAND_ERR_FORMAT;
                    }
                    else
                    {
                        if (keyValue.Length == 1)
                        {
                            result = DecodeResult.COMMAND_NONE_VALUE;
                        }
                        else
                        {
                            value = keyValue[1].Trim;
                            if (value.Length == 0)
                            {
                                result = DecodeResult.COMMAND_NONE_VALUE;
                                value  = null;
                            }
                            else
                            {
                                result = DecodeResult.COMMAND_OK;
                            }
                        }
                    }
                }
                CommandFinishHandler(result, key, value);
            }
        }
示例#33
0
 public static UInt32 DecodeARM32(UInt32 cur_inst, out DecodeResult type)
 {
     // if this doesn't change, error
     type = DecodeResult.INSTRUCTION_UNKNOWN;
     // Bits 31-28 should be 1110, Always Execute
     if (!(BitSet(cur_inst, 31) && BitSet(cur_inst, 30) && BitSet(cur_inst, 29) && !BitSet(cur_inst, 28)))
     {
         // Unsupported conditional instruction.
         return(0);
     }
     // Bits 27-25 should be 110 for supervisor calls
     if (BitSet(cur_inst, 27))
     {
         // Bit 24 should be set for SWI calls
         if (BitSet(cur_inst, 26) && BitSet(cur_inst, 25) && BitSet(cur_inst, 24))
         {
             type = DecodeResult.INSTRUCTION_SYSCALL;
             // TODO: Return syscall immediate value.
             return(1);
         }
     }
     // Bits 27-25 should be 001 for data instructions
     else if (!BitSet(cur_inst, 26) && BitSet(cur_inst, 25))
     {
         // Bits 24-23 should be 10
         if (!(BitSet(cur_inst, 24) && !BitSet(cur_inst, 23)))
         {
             // Not an valid ARM MOV instruction.
             return(0);
         }
         // Bits 21-20 should be 00
         if (!(!BitSet(cur_inst, 21) && !BitSet(cur_inst, 20)))
         {
             // Invalid ARM MOV instruction.
             return(0);
         }
         // Bit 22 is 1 for top load 0 for bottom load
         if (BitSet(cur_inst, 22)) // top load
         {
             type = DecodeResult.INSTRUCTION_MOVT;
         }
         else
         {
             type = DecodeResult.INSTRUCTION_MOVW;
         }
         // Immediate value at 19-16 and 11-0
         // discard bytes 31-20
         // discard bytes 15-0
         return((((cur_inst << 12) >> 28) << 12) | ((cur_inst << 20) >> 20));
     }
     // Bits 27-25 should be 000 for jump instructions
     else if (!BitSet(cur_inst, 26) && !BitSet(cur_inst, 25))
     {
         // Bits 24-4 should be 100101111111111110001, 0x12FFF1 for BX
         if ((cur_inst << 7) >> 11 == 0x12FFF1)
         {
             type = DecodeResult.INSTRUCTION_BRANCH;
             return(0);
         }
         // Bits 24-4 should be 100101111111111110011, 0x12FFF3 for BLX
         else if ((cur_inst << 7) >> 11 == 0x12FFF3)
         {
             type = DecodeResult.INSTRUCTION_BRANCH;
             return(0);
         }
         else
         {
             // unknown jump
             return(0);
         }
     }
     else
     {
         // Unsupported instruction.
         return(0);
     }
     return(0);
 }