Пример #1
0
        ////////////////////////////////////////////////////////////////////
        // Encode input byte array into QRCode boolean matrix
        ////////////////////////////////////////////////////////////////////

        internal Byte[,] EncodeQRCode
        (
            String DataString,
            ErrorCorrection ErrorCorrection
        )
        {
            // make sure data string is not empty
            if (String.IsNullOrEmpty(DataString))
            {
                throw new ApplicationException("Input data string is null or empty");
            }

            // split input data string to segments delimited by SegmentMarker
            SegDataString = DataString.Split(new Char[] { PdfQRCode.SegmentMarker }, StringSplitOptions.RemoveEmptyEntries);
            if (SegDataString == null || SegDataString.Length == 0)
            {
                throw new ApplicationException("Input data string is null or empty");
            }

            // create encoding mode array
            SegEncodingMode = new EncodingMode[SegDataString.Length];

            // create QR code boolean aray
            return(EncodeQRCode(ErrorCorrection));
        }
        public override string GetFFMpegCommand(EncodingMode encodingMode)
        {
            string hdrParameters = "";

            if (ColorInfo != null)
            {
                hdrParameters = $"hdr-opt=1:repeat-headers=1:colorprim={ColorInfo.ColorPrimaries}:transfer={ColorInfo.ColorTransfer}:colormatrix={ColorInfo.ColorSpace}:master-display={ColorInfo.DisplayMetadata}:max-cll={ColorInfo.LightLevelMetadata.maxContent},{ColorInfo.LightLevelMetadata.maxAverage}";
            }

            string command = encodingMode switch
            {
                EncodingMode.ConstantQuality => $"libx265 -preset {Preset.GetName().Replace(" ", "").ToLower()} -crf {Crf} {(ColorInfo != null ? $"-x265-params {hdrParameters}" : "")}",
                EncodingMode.AverageBitrate_SinglePass => $"libx265 -preset {Preset.GetName().Replace(" ", "").ToLower()} -b:v {Bitrate.Kbps}k {(ColorInfo != null ? $"-x265-params {hdrParameters}" : "")}",
                EncodingMode.AverageBitrate_FirstPass => $"libx265 -preset {Preset.GetName().Replace(" ", "").ToLower()} -b:v {Bitrate.Kbps}k -x265-params pass=1",
                EncodingMode.AverageBitrate_SecondPass => $"libx265 -preset {Preset.GetName().Replace(" ", "").ToLower()} -b:v {Bitrate.Kbps}k -x265-params pass=2{(ColorInfo != null ? $":{hdrParameters}" : "")}",
                _ => "",
            };

            if (PixelFormat != PixelFormat.copy)
            {
                command += $" -pix_fmt {PixelFormat}";
            }

            return(command);
        }
Пример #3
0
 public Code16KEncoder(Symbology symbology, string barcodeMessage, EncodingMode encodingMode)
 {
     this.symbolId             = symbology;
     this.barcodeMessage       = barcodeMessage;
     this.encodingMode         = encodingMode;
     this.elementsPerCharacter = 11;
 }
Пример #4
0
 public State(EncodingMode mode, IToken tokens, int shiftByteCount, int bitCount)
 {
     Mode           = mode;
     Tokens         = tokens;
     ShiftByteCount = shiftByteCount;
     BitCount       = bitCount;
 }
        public string ReadDataAboutPositionAsString(long position, int SizeArea)
        {
            List <byte> bytes = new List <byte>(ReadBaseBytes(position - SizeArea, position));

            bytes.AddRange(ReadBaseBytes(position, position + SizeArea));
            return(EncodingMode.GetString(bytes.ToArray()));
        }
Пример #6
0
        public override (BitList, VersionInfo) Encode(string content, ErrorCorrectionLevel errorCorrectionLevel)
        {
            if (content == null)
            {
                throw new ArgumentNullException(nameof(content));
            }
            byte[] data = TextEncoding.UTF8.GetBytes(content);

            EncodingMode encodingMode = EncodingMode.Byte;
            var          versionInfo  = VersionInfo.FindSmallestVersionInfo(errorCorrectionLevel, encodingMode, data.Length * 8);

            if (versionInfo == null)
            {
                throw new InvalidOperationException("Too much data to encode");
            }

            var bits = new BitList();

            bits.AddBits((uint)encodingMode, 4);
            bits.AddBits((uint)content.Length, versionInfo.CharCountBits(encodingMode));
            foreach (var b in data)
            {
                bits.AddByte(b);
            }
            AddPaddingAndTerminator(ref bits, versionInfo);
            return(bits, versionInfo);
        }
Пример #7
0
        /// <summary>
        /// インスタンスを初期化します。
        /// </summary>
        /// <param name="parent">親オブジェクト</param>
        internal Symbol(Symbols parent)
        {
            _parent = parent;

            _position = parent.Count;

            _currEncoder      = null;
            _currEncodingMode = EncodingMode.UNKNOWN;
            _currVersion      = parent.MinVersion;

            _dataBitCapacity = 8 * DataCodeword.GetTotalNumber(
                parent.ErrorCorrectionLevel, parent.MinVersion);
            _dataBitCounter = 0;

            _segments       = new List <QRCodeEncoder>();
            _segmentCounter = new Dictionary <EncodingMode, int>()
            {
                { EncodingMode.NUMERIC, 0 },
                { EncodingMode.ALPHA_NUMERIC, 0 },
                { EncodingMode.EIGHT_BIT_BYTE, 0 },
                { EncodingMode.KANJI, 0 }
            };

            if (parent.StructuredAppendAllowed)
            {
                _dataBitCapacity -= StructuredAppend.HEADER_LENGTH;
            }
        }
Пример #8
0
 public KernelSetting(string appId, string appSecret, EncodingMode encodingMode = EncodingMode.Plain, string encodingAesKey = "")
 {
     AppId          = appId;
     AppSecret      = appSecret;
     EncodingMode   = encodingMode;
     EncodingAesKey = encodingAesKey;
 }
        /// <summary>
        /// Finishes constructor work.
        /// </summary>
        private void Initialize(IEnumerable <string> templateFolderRoots, EncodingMode encodingMode)
        {
            if (templateFolderRoots == null)
            {
                throw new ArgumentNullException(nameof(templateFolderRoots));
            }

            this.TemplateFolderRoots = templateFolderRoots;

            var configuration = new TemplateServiceConfiguration()
            {
#if DEBUG
                Debug = true,
#endif
                TemplateManager = new ResolvePathTemplateManager(templateFolderRoots),
            };

            switch (encodingMode)
            {
            case EncodingMode.RawText:
                configuration.EncodedStringFactory = new RawStringFactory();
                break;

            default:
                configuration.EncodedStringFactory = new HtmlEncodedStringFactory();
                break;
            }

            this.razorEngineService = RazorEngineService.Create(configuration);
        }
Пример #10
0
        // Create a new state representing this state, but an additional character
        // output in Binary Shift mode.
        public State AddBinaryShiftChar(int index)
        {
            IToken       tokens   = Tokens;
            EncodingMode mode     = Mode;
            int          bitCount = BitCount;

            if (Mode == EncodingMode.Punct || Mode == EncodingMode.Digit)
            {
                var latch = LatchTable[Mode][EncodingMode.Upper];
                tokens    = new SimpleToken(tokens, latch & 0xFFFF, (byte)(latch >> 16));
                bitCount += (int)(latch >> 16);
                mode      = EncodingMode.Upper;
            }

            int deltaBitCount = 8;

            if (ShiftByteCount == 0 || ShiftByteCount == 31)
            {
                deltaBitCount = 18;
            }
            else if (ShiftByteCount == 62)
            {
                deltaBitCount = 9;
            }

            var result = new State(mode, tokens, ShiftByteCount + 1, bitCount + deltaBitCount);

            if (result.ShiftByteCount == 2047 + 31)
            {
                // The string is as long as it's allowed to be.  We should end it.
                result = result.EndBinaryShift(index + 1);
            }

            return(result);
        }
        public override string GetFFMpegCommand(EncodingMode encodingMode)
        {
            // string hdrParameters = "";

            // if (ColorInfo != null)
            // {
            // hdrParameters = $"colorprim={ColorInfo.ColorPrimaries}:transfer={ColorInfo.ColorTransfer}:colormatrix={ColorInfo.ColorSpace}:master-display={ColorInfo.DisplayMetadata}:max-cll={ColorInfo.LightLevelMetadata.maxContent},{ColorInfo.LightLevelMetadata.maxAverage}";
            // }

            // TODO: add a method that finds the ideal tiles settings
            // TODO: add hdr support
            string command = encodingMode switch
            {
                EncodingMode.ConstantQuality => $"libaom-av1 -cpu-used {CPU_Used} -row-mt 1 -tiles 2x2 -crf {Crf} -b:v 0",
                EncodingMode.AverageBitrate_SinglePass => $"libaom-av1 -cpu-used {CPU_Used} -row-mt 1 -tiles 2x2 -b:v {Bitrate.Kbps}k",
                EncodingMode.AverageBitrate_FirstPass => $"libaom-av1 -cpu-used {CPU_Used} -row-mt 1 -tiles 2x2 -b:v {Bitrate.Kbps}k -pass 1",
                EncodingMode.AverageBitrate_SecondPass => $"libaom-av1 -cpu-used {CPU_Used} -row-mt 1 -tiles 2x2 -b:v {Bitrate.Kbps}k -pass 2",
                _ => "",
            };

            if (PixelFormat != PixelFormat.copy)
            {
                command += $" -pix_fmt {PixelFormat}";
            }

            return(command);
        }
Пример #12
0
        /// <summary>
        /// 符号化モードを設定します。
        /// </summary>
        /// <param name="encMode">符号化モード</param>
        /// <param name="c">符号化する最初の文字。この文字はシンボルに追加されません。</param>
        /// <returns>シンボル容量が不足している場合は false を返します。</returns>
        internal bool TrySetEncodingMode(EncodingMode encMode, char c)
        {
            QRCodeEncoder encoder;
            Encoding      encoding = _parent.Encoding;

            switch (encMode)
            {
            case EncodingMode.NUMERIC:
                encoder = new NumericEncoder(encoding);
                break;

            case EncodingMode.ALPHA_NUMERIC:
                encoder = new AlphanumericEncoder(encoding);
                break;

            case EncodingMode.EIGHT_BIT_BYTE:
                encoder = new ByteEncoder(encoding);
                break;

            case EncodingMode.KANJI:
                if (Charset.IsJP(encoding.WebName))
                {
                    encoder = new KanjiEncoder(encoding);
                }
                else
                {
                    throw new InvalidOperationException();
                }
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(encMode));
            }

            int bitLength = encoder.GetCodewordBitLength(c);

            while (_dataBitCapacity <
                   _dataBitCounter
                   + ModeIndicator.LENGTH
                   + CharCountIndicator.GetLength(_currVersion, encMode)
                   + bitLength)
            {
                if (_currVersion >= _parent.MaxVersion)
                {
                    return(false);
                }

                SelectVersion();
            }

            _dataBitCounter += ModeIndicator.LENGTH
                               + CharCountIndicator.GetLength(_currVersion, encMode);
            _currEncoder = encoder;
            _segments.Add(_currEncoder);
            _segmentCounter[encMode]++;
            _currEncodingMode = encMode;

            return(true);
        }
Пример #13
0
        ////////////////////////////////////////////////////////////////////
        // Encode input byte array into QRCode boolean matrix
        ////////////////////////////////////////////////////////////////////

        private void EncodeQRCode
        (
            ErrorCorrection ErrorCorrection,
            Int32 QuietZone
        )
        {
            // test input
            if (SegDataString == null || SegDataString.Length == 0)
            {
                throw new ApplicationException("Input data strings are null or empty");
            }

            // create encoding mode array
            SegEncodingMode = new EncodingMode[SegDataString.Length];

            // initialization
            Initialization(ErrorCorrection);

            // encode data
            EncodeData();

            // calculate error correction
            CalculateErrorCorrection();

            // iterleave data and error correction codewords
            InterleaveBlocks();

            // build base matrix
            BuildBaseMatrix();

            // load base matrix with data and error correction codewords
            LoadMatrixWithData();

            // data masking
            SelectBastMask();

            // add format information (error code level and mask code)
            AddFormatInformation();

            // output matrix size in pixels
            Int32 SidePix = MatrixDimension + 2 * QuietZone;

            OutputMatrix = new Boolean[SidePix, SidePix];

            // convert result matrix to output matrix
            for (Int32 Row = 0; Row < MatrixDimension; Row++)
            {
                for (Int32 Col = 0; Col < MatrixDimension; Col++)
                {
                    if ((ResultMatrix[Row, Col] & 1) != 0)
                    {
                        OutputMatrix[QuietZone + Row, QuietZone + Col] = true;
                    }
                }
            }

            // output array
            return;
        }
Пример #14
0
 private void hibcRadioButton_CheckedChanged(object sender, EventArgs e)
 {
     if (hibcRadioButton.Checked)
     {
         encodingMode = EncodingMode.HIBC;
         imagePanel.Invalidate();
     }
 }
Пример #15
0
        /**
         * Creates an instance and fills the fields based on ... the fields
         */

        public Ole10Native(string label, string filename, string command, byte[] data)
        {
            Label      = (label);
            FileName   = (filename);
            Command    = (command);
            DataBuffer = (data);
            mode       = EncodingMode.parsed;
        }
Пример #16
0
        public void PopulateMatrix(
            string text,
            int errorCorrectionLevel,
            EncodingMode mode,
            int columns,
            int rows)
        {
            this.encodedRawData = new List <long>();
            this.xRatio         = this.GetValidValue(columns, 3, 30);
            this.yRatio         = this.GetValidValue(rows, 2, 90);
            this.eCLevel        = errorCorrectionLevel;
            this.eCCount        = SpecificationData.ErrorCorrectionLevels[this.eCLevel].Count;
            switch (mode)
            {
            case EncodingMode.Auto:
                text = PDF417.ValidateTextModeNone(text);
                int dataIndex = 0;
                while (dataIndex < text.Length)
                {
                    int digitsAtPosition = PDF417.GetNumberOfDigitsAtPosition(text, dataIndex);
                    if (digitsAtPosition >= 13)
                    {
                        this.EncodeNumeric(text, ref dataIndex, digitsAtPosition);
                    }
                    else if (digitsAtPosition < 13)
                    {
                        int ofCharsAtPosition = PDF417.GetNumberOfCharsAtPosition(text, dataIndex);
                        if (ofCharsAtPosition >= 5)
                        {
                            this.EncodeText(text, ref dataIndex, ofCharsAtPosition);
                        }
                        else if (ofCharsAtPosition < 5)
                        {
                            int ofBytesAtPosition = PDF417.GetNumberOfBytesAtPosition(text, dataIndex);
                            this.EncodeByte(text, ref dataIndex, ofBytesAtPosition);
                        }
                    }
                }
                break;

            case EncodingMode.Text:
                this.EncodeTextCompleteString(text);
                break;

            case EncodingMode.Numeric:
                this.EncodeNumericCompleteString(text);
                break;

            default:
                this.EncodeByteCompleteString(text);
                break;
            }
            this.SetSmallestSizeOfMatrix();
            this.VerifyDataLength();
            this.PadData();
            this.SetErrorCorrection();
            this.FillMatrixWithData();
        }
Пример #17
0
        public static int[] Encode(string data)
        {
            EncodingMode encodingMode = EncodingMode.Text;
            SubMode      textSubMode  = SubMode.Upper;

            var result = new List <int>();

            while (data.Length > 0)
            {
                var numericCount = DetermineConsecutiveDigitCount(data);
                if (numericCount >= MinNumericCount || numericCount == data.Length)
                {
                    result.Add(LatchToNumeric);
                    encodingMode = EncodingMode.Numeric;
                    textSubMode  = SubMode.Upper;
                    IEnumerable <int> numData = EncodeNumeric(data.Substring(0, numericCount));
                    result.AddRange(numData);
                    data = data.Substring(numericCount);
                }
                else
                {
                    var textCount = DetermineConsecutiveTextCount(data);
                    if (textCount >= 5 || textCount == data.Length)
                    {
                        if (encodingMode != EncodingMode.Text)
                        {
                            result.Add(LatchToText);
                            encodingMode = EncodingMode.Text;
                            textSubMode  = SubMode.Upper;
                        }

                        IEnumerable <int> txtData = EncodeText(EncodeTextPreprocess(data.Substring(0, textCount), ref textSubMode));
                        result.AddRange(txtData);
                        data = data.Substring(textCount);
                    }
                    else
                    {
                        var binaryCount = DetermineConsecutiveBinaryCount(data);
                        if (binaryCount == 0)
                        {
                            binaryCount = 1;
                        }

                        string bytes = data.Substring(0, binaryCount);
                        if (bytes.Length != 1 || encodingMode != EncodingMode.Text)
                        {
                            encodingMode = EncodingMode.Binary;
                            textSubMode  = SubMode.Upper;
                        }
                        IEnumerable <int> byteData = EncodeBinary(bytes, encodingMode);
                        result.AddRange(byteData);
                        data = data.Substring(binaryCount);
                    }
                }
            }

            return(result.ToArray());
        }
        /// <summary>
        /// Create.
        /// </summary>
        /// <param name="templateFolderRoots">
        /// A collection of folder roots to search for Razor templates.
        /// These can be relative paths, which will be transformed to absolute
        /// based on the application's root.
        /// </param>
        /// <param name="encodingMode">
        /// The escaping to use for strings generated from templates.
        /// </param>
        public RazorEngineRenderProvider(string[] templateFolderRoots, EncodingMode encodingMode)
        {
            if (templateFolderRoots == null)
            {
                throw new ArgumentNullException(nameof(templateFolderRoots));
            }

            Initialize(templateFolderRoots.SelectMany(f => NormalizePath(f)), encodingMode);
        }
Пример #19
0
 private void standardRadioButton_CheckedChanged(object sender, EventArgs e)
 {
     if (standardRadioButton.Checked)
     {
         encodingMode = EncodingMode.Standard;
         SetBarcodeProperties();
         imagePanel.Invalidate();
     }
 }
        /// <summary>
        /// Create.
        /// </summary>
        /// <param name="templateFolderRoot">
        /// A folder root to search for Razor templates.
        /// It can be relative a path, which will be transformed to absolute
        /// based on the application's root.
        /// </param>
        /// <param name="encodingMode">
        /// The escaping to use for strings generated from templates.
        /// </param>
        public RazorEngineRenderProvider(string templateFolderRoot, EncodingMode encodingMode)
        {
            if (templateFolderRoot == null)
            {
                throw new ArgumentNullException(nameof(templateFolderRoot));
            }

            Initialize(NormalizePath(templateFolderRoot), encodingMode);
        }
Пример #21
0
        // Create a new state representing this state, with a temporary shift
        // to a different mode to output a single value.
        public State ShiftAndAppend(EncodingMode mode, uint value)
        {
            IToken tokens = Tokens;

            // Shifts exist only to UPPER and PUNCT, both with tokens size 5.
            tokens = new SimpleToken(tokens, ShiftTable[Mode][mode], Mode.BitCount());
            tokens = new SimpleToken(tokens, value, 5);

            return(new State(Mode, tokens, 0, BitCount + Mode.BitCount() + 5));
        }
Пример #22
0
 public ConversionOptions(VideoEncoder encoder)
 {
     Encoder                = encoder;
     NoAudio                = false;
     EncodingMode           = 0;
     EncodeSections         = new TimeIntervalCollection(TimeSpan.Zero);
     AudioConversionOptions = new Dictionary <int, AudioConversionOptions>();
     Filters                = new List <IFilter>();
     FadeEffect             = false;
 }
Пример #23
0
 public PDF417Encoder(Symbology symbology, string barcodeMessage, int optionDataColumns,
                      int optionErrorCorrection, int optionElementHeight, EncodingMode encodingMode)
 {
     this.symbolId              = symbology;
     this.barcodeMessage        = barcodeMessage;
     this.optionDataColumns     = optionDataColumns;
     this.optionErrorCorrection = optionErrorCorrection;
     this.optionElementHeight   = optionElementHeight;
     this.encodingMode          = encodingMode;
 }
Пример #24
0
        internal static IEnumerable <int> EncodeBinary(string data, EncodingMode startMode)
        {
            var result = new List <int>();

            int count = data.Length;

            if (count == 1 && startMode == EncodingMode.Text)
            {
                result.Add(ShiftToByte);
            }
            else if ((count % 6) == 0)
            {
                result.Add(LatchToByte);
            }
            else
            {
                result.Add(LatchToBytePadded);
            }

            int idx = 0;

            // Encode six-packs
            if (count >= 6)
            {
                var words = new int[5];
                while ((count - idx) >= 6)
                {
                    long t = 0L;
                    for (int i = 0; i < 6; i++)
                    {
                        t  = t << 8;
                        t += data[idx + i];
                    }

                    for (int i = 0; i < 5; i++)
                    {
                        words[4 - i] = (int)(t % 900);
                        t            = t / 900;
                    }

                    result.AddRange(words);
                    idx += 6;
                }
            }

            // Encode rest (remaining n < 5 bytes if any)
            for (int i = idx; i < count; i++)
            {
                result.Add(data[i] & 0xFF);
            }

            return(result);
        }
Пример #25
0
        public override (BitList, VersionInfo) Encode(string content, ErrorCorrectionLevel errorCorrectionLevel)
        {
            if (content == null)
            {
                throw new ArgumentNullException(nameof(content));
            }
            bool contentLengthIsOdd = content.Length % 2 == 1;
            int  contentBitCount    = (content.Length / 2) * 11;

            if (contentLengthIsOdd)
            {
                contentBitCount += 6;
            }

            EncodingMode encodingMode = EncodingMode.AlphaNumeric;
            var          versionInfo  = VersionInfo.FindSmallestVersionInfo(errorCorrectionLevel, encodingMode, contentBitCount);

            if (versionInfo == null)
            {
                throw new InvalidOperationException("Too much data to encode");
            }

            var bits = new BitList();

            bits.AddBits((uint)encodingMode, 4);
            bits.AddBits((uint)content.Length, versionInfo.CharCountBits(encodingMode));

            var encoder = new Queue <int>(content.Select(x => CharSet.IndexOf(x)));

            for (int i = 0; i < content.Length / 2; i++)
            {
                int c1 = encoder.Dequeue();
                int c2 = encoder.Dequeue();
                if (c1 < 0 || c2 < 0)
                {
                    throw new InvalidOperationException($"{content} can not be ancoded as {encodingMode}");
                }
                bits.AddBits((uint)(c1 * 45 + c2), 11);
            }

            if (contentLengthIsOdd)
            {
                int c = encoder.Dequeue();
                if (c < 0)
                {
                    throw new InvalidOperationException($"{content} can not be ancoded as {encodingMode}");
                }
                bits.AddBits((uint)c, 6);
            }

            AddPaddingAndTerminator(ref bits, versionInfo);
            return(bits, versionInfo);
        }
Пример #26
0
        internal static int GetLengthIndicatorLength(int codeVersion, EncodingMode mode)
        {
            switch (mode)
            {
            case EncodingMode.Numeric:
                if (codeVersion < 10)
                {
                    return(10);
                }
                if (codeVersion > 26)
                {
                    return(14);
                }
                return(12);

            case EncodingMode.AlphaNumeric:
                if (codeVersion < 10)
                {
                    return(9);
                }
                if (codeVersion > 26)
                {
                    return(11);
                }
                return(13);

            case EncodingMode.Bytes:
                if (codeVersion < 10)
                {
                    return(8);
                }
                if (codeVersion > 26)
                {
                    return(16);
                }
                return(16);

            case EncodingMode.Kanji:
                if (codeVersion < 10)
                {
                    return(8);
                }
                if (codeVersion > 26)
                {
                    return(10);
                }
                return(12);

            default:
                throw new Exception("Wrong Encoding Mode!");
            }
        }
Пример #27
0
        // Return a set of states that represent the possible ways of updating this
        // state for the next character.  The resulting set of states are added to
        // the "result" list.
        private static State[] UpdateStateForChar(State state, byte[] data, int index)
        {
            State[] result             = null;
            var     ch                 = data[index];
            var     charInCurrentTable = State.CharMap[state.Mode][ch] > 0;

            State?stateNoBinary = null;

            for (EncodingMode mode = EncodingMode.Upper; mode <= EncodingMode.Punct; mode++)
            {
                var charInMode = State.CharMap[mode][ch];
                if (charInMode > 0)
                {
                    if (!stateNoBinary.HasValue)
                    {
                        // Only create stateNoBinary the first time it's required.
                        stateNoBinary = state.EndBinaryShift(index);
                    }

                    // Try generating the character by latching to its mode
                    if (!charInCurrentTable || mode == state.Mode || mode == EncodingMode.Digit)
                    {
                        // If the character is in the current table, we don't want to latch to
                        // any other mode except possibly digit (which uses only 4 bits).  Any
                        // other latch would be equally successful *after* this character, and
                        // so wouldn't save any bits.
                        State res = stateNoBinary.Value.LatchAndAppend(mode, charInMode);
                        result = (result ?? Array.Empty <State>()).Append(res).ToArray();
                    }

                    // Try generating the character by switching to its mode.
                    if (!charInCurrentTable && State.ShiftTable.ContainsKey(state.Mode) && State.ShiftTable[state.Mode].ContainsKey(mode))
                    {
                        // It never makes sense to temporarily shift to another mode if the
                        // character exists in the current mode.  That can never save bits.
                        State res = stateNoBinary.Value.ShiftAndAppend(mode, charInMode);
                        result = (result ?? Array.Empty <State>()).Append(res).ToArray();
                    }
                }
            }

            if (state.ShiftByteCount > 0 || State.CharMap[state.Mode][ch] == 0)
            {
                // It's never worthwhile to go into binary shift mode if you're not already
                // in binary shift mode, and the character exists in your current mode.
                // That can never save bits over just outputting the char in the current mode.
                State res = state.AddBinaryShiftChar(index);
                result = (result ?? Array.Empty <State>()).Append(res).ToArray();
            }

            return(result);
        }
Пример #28
0
 internal static bool TryParse(int value, out EncodingMode mode)
 {
     if (Enum.IsDefined(typeof(EncodingMode), value))
     {
         mode = (EncodingMode)value;
         return(true);
     }
     else
     {
         mode = EncodingMode.Byte;
         return(false);
     }
 }
        public override string GetFFMpegCommand(EncodingMode encodingMode)
        {
            switch (encodingMode)
            {
            case EncodingMode.ConstantQuality:
                return($"hevc_nvenc -profile rext -preset medium -rc vbr_hq -rc-lookahead 32 -cq {Cq} -qmin {Cq} -qmax {Cq} -bf 3 -b_ref_mode middle -pix_fmt yuv420p");

            case EncodingMode.AverageBitrate_SinglePass:
                return($"hevc_nvenc -profile rext -preset medium -rc vbr_hq -rc-lookahead 32 -b:v {Bitrate}k -bf 3 -b_ref_mode middle -pix_fmt yuv420p");

            default:
                return("");
            }
        }
        public override string GetFFMpegCommand(EncodingMode encodingMode)
        {
            switch (encodingMode)
            {
            case EncodingMode.ConstantQuality:
                return($"hevc_qsv -profile main -preset {Preset.GetName().Replace(" ", "").ToLower()} -global_quality {GlobalQuality} -look_ahead 1 -pix_fmt yuv420p");

            case EncodingMode.AverageBitrate_SinglePass:
                return($"hevc_qsv -profile main -preset {Preset.GetName().Replace(" ", "").ToLower()} -b:v {Bitrate}k -look_ahead 1 -pix_fmt yuv420p");

            default:
                return("");
            }
        }
Пример #31
0
        ////////////////////////////////////////////////////////////////////
        // Encode input byte array into QRCode boolean matrix
        ////////////////////////////////////////////////////////////////////
        internal Byte[,] EncodeQRCode(
			String			DataString,
			ErrorCorrection	ErrorCorrection
			)
        {
            // make sure data string is not empty
            if(String.IsNullOrEmpty(DataString)) throw new ApplicationException("Input data string is null or empty");

            // split input data string to segments delimited by SegmentMarker
            SegDataString = DataString.Split(new Char[] {PdfQRCode.SegmentMarker}, StringSplitOptions.RemoveEmptyEntries);
            if(SegDataString == null || SegDataString.Length == 0) throw new ApplicationException("Input data string is null or empty");

            // create encoding mode array
            SegEncodingMode = new EncodingMode[SegDataString.Length];

            // create QR code boolean aray
            return(EncodeQRCode(ErrorCorrection));
        }
Пример #32
0
 private bool IsUtf8(EncodingMode encoding, string plainText)
 {
     return (encoding == EncodingMode.Byte && !this.IsValidISO(plainText));
 }
Пример #33
0
 private string PlainTextToBinary(string plainText, EncodingMode encMode, bool utf8BOM, bool forceUtf8)
 {
     if (encMode.Equals(EncodingMode.Numeric))
         return this.PlainTextToBinaryNumeric(plainText);
     else if (encMode.Equals(EncodingMode.Alphanumeric))
         return this.PlainTextToBinaryAlphanumeric(plainText);
     else if (encMode.Equals(EncodingMode.Byte))
         return this.PlainTextToBinaryByte(plainText, utf8BOM, forceUtf8);
     else
         return string.Empty;
 }
Пример #34
0
 private int GetDataLength(EncodingMode encoding, string plainText, string codedText, bool forceUtf8)
 {
     return forceUtf8 || this.IsUtf8(encoding, plainText) ? (codedText.Length / 8) : plainText.Length;
 }
Пример #35
0
 private int GetVersion(int length, EncodingMode encMode, ECCLevel eccLevel)
 {
     var version = this.capacityTable.Where(
         x => x.Details.Count(
             y => (y.ErrorCorrectionLevel == eccLevel
                   && y.CapacityDict[encMode] >= Convert.ToInt32(length)
                   )
             ) > 0
       ).Select(x => new
       {
           version = x.Version,
           capacity = x.Details.Single(y => y.ErrorCorrectionLevel == eccLevel)
                                     .CapacityDict[encMode]
       }).Min(x => x.version);
     return version;
 }
Пример #36
0
        /**
         * Creates an instance and Fills the fields based on the data in the given buffer.
         *
         * @param data   The buffer Containing the Ole10Native record
         * @param offset The start offset of the record in the buffer
         * @throws Ole10NativeException on invalid or unexcepted data format
         */
        public Ole10Native(byte[] data, int offset)
        {
            int ofs = offset;        // current offset, Initialized to start

            if (data.Length < offset + 2)
            {
                throw new Ole10NativeException("data is too small");
            }

            totalSize = LittleEndian.GetInt(data, ofs);
            ofs += LittleEndianConsts.INT_SIZE;
            mode = EncodingMode.unparsed;
            if (LittleEndian.GetShort(data, ofs) == 2)
            {
                // some files like equations don't have a valid filename,
                // but somehow encode the formula right away in the ole10 header
                if (char.IsControl((char)data[ofs + LittleEndianConsts.SHORT_SIZE]))
                {
                    mode = EncodingMode.compact;
                }
                else
                {
                    mode = EncodingMode.parsed;
                }
            }
            int dataSize = 0;
            switch (mode)
            {
                case EncodingMode.parsed:
                    flags1 = LittleEndian.GetShort(data, ofs);
                    ofs += LittleEndianConsts.SHORT_SIZE;
                    int len = GetStringLength(data, ofs);
                    label = StringUtil.GetFromCompressedUnicode(data, ofs, len - 1);
                    ofs += len;
                    len = GetStringLength(data, ofs);
                    fileName = StringUtil.GetFromCompressedUnicode(data, ofs, len - 1);
                    ofs += len;
                    flags2 = LittleEndian.GetShort(data, ofs);
                    ofs += LittleEndianConsts.SHORT_SIZE;

                    unknown1 = LittleEndian.GetShort(data, ofs);
                    ofs += LittleEndianConsts.SHORT_SIZE;

                    len = LittleEndian.GetInt(data, ofs);
                    ofs += LittleEndianConsts.INT_SIZE;

                    command = StringUtil.GetFromCompressedUnicode(data, ofs, len - 1);
                    ofs += len;
                    if (totalSize < ofs)
                    {
                        throw new Ole10NativeException("Invalid Ole10Native");
                    }

                    dataSize = LittleEndian.GetInt(data, ofs);
                    ofs += LittleEndianConsts.INT_SIZE;

                    if (dataSize < 0 || totalSize - (ofs - LittleEndianConsts.INT_SIZE) < dataSize)
                    {
                        throw new Ole10NativeException("Invalid Ole10Native");
                    }

                    break;
                case EncodingMode.compact:
                    flags1 = LittleEndian.GetShort(data, ofs);
                    ofs += LittleEndianConsts.SHORT_SIZE;
                    dataSize = totalSize - LittleEndianConsts.SHORT_SIZE;
                    break;
                case EncodingMode.unparsed:
                    dataSize = totalSize;
                    break;

            }
            dataBuffer = new byte[dataSize];
            Array.Copy(data, ofs, dataBuffer, 0, dataSize);
            ofs += dataSize;

        }
Пример #37
0
 private int GetCountIndicatorLength(int version, EncodingMode encMode)
 {
     if (version < 10)
     {
         if (encMode.Equals(EncodingMode.Numeric))
             return 10;
         else if (encMode.Equals(EncodingMode.Alphanumeric))
             return 9;
         else
             return 8;
     }
     else if (version < 27)
     {
         if (encMode.Equals(EncodingMode.Numeric))
             return 12;
         else if (encMode.Equals(EncodingMode.Alphanumeric))
             return 11;
         else if (encMode.Equals(EncodingMode.Byte))
             return 16;
         else
             return 10;
     }
     else
     {
         if (encMode.Equals(EncodingMode.Numeric))
             return 14;
         else if (encMode.Equals(EncodingMode.Alphanumeric))
             return 13;
         else if (encMode.Equals(EncodingMode.Byte))
             return 16;
         else
             return 12;
     }
 }
Пример #38
0
        void boxVariable_CheckedChanged(object sender, EventArgs e)
        {
            if (!(sender as RadioButton).Checked) return;

            tableVideoVariableOptions.BringToFront();
            tableAudioVariableOptions.BringToFront();
            encodingMode = EncodingMode.Variable;
            numericCrf.TabStop = numericCrfTolerance.TabStop = numericAudioQuality.TabStop = true;
            boxLimit.TabStop = boxBitrate.TabStop = boxAudioBitrate.TabStop = false;

            buttonConstantDefault.Visible = false;
            if (encodingMode != Properties.Settings.Default.EncodingMode)
            {
                buttonVariableDefault.Visible = true;
            }

            UpdateArguments(sender, e);

            opusQualityScalingTooltip();
        }
 private static bool IsUtf8(EncodingMode encoding, string plainText)
 {
     return (encoding == EncodingMode.Byte && !IsValidIso(plainText));
 }
Пример #40
0
 private string PlainTextToBinary(string plainText, EncodingMode encMode)
 {
     if (encMode.Equals(EncodingMode.Numeric))
         return PlainTextToBinaryNumeric(plainText);
     else if (encMode.Equals(EncodingMode.Alphanumeric))
         return PlainTextToBinaryAlphanumeric(plainText);
     else if (encMode.Equals(EncodingMode.Byte))
         return PlainTextToBinaryByte(plainText);
     else
         return string.Empty;
 }
 private static int GetCountIndicatorLength(int version, EncodingMode encMode)
 {
     if (version < 10)
     {
         if (encMode.Equals(EncodingMode.Numeric))
             return 10;
         return encMode.Equals(EncodingMode.Alphanumeric) ? 9 : 8;
     }
     if (version < 27)
     {
         if (encMode.Equals(EncodingMode.Numeric))
             return 12;
         if (encMode.Equals(EncodingMode.Alphanumeric))
             return 11;
         return encMode.Equals(EncodingMode.Byte) ? 16 : 10;
     }
     if (encMode.Equals(EncodingMode.Numeric))
         return 14;
     if (encMode.Equals(EncodingMode.Alphanumeric))
         return 13;
     return encMode.Equals(EncodingMode.Byte) ? 16 : 12;
 }
Пример #42
0
        ////////////////////////////////////////////////////////////////////
        // Get some values
        ////////////////////////////////////////////////////////////////////
        //internal Int32			Version {get{return(version);}}
        //internal Int32			MatrixDimension {get{return(matrixDimension);}}
        //internal ErrorCorrection	ErrorCorrection {get{return(errorCorrection);}}
        ////////////////////////////////////////////////////////////////////
        // Set encoded data bits length
        ////////////////////////////////////////////////////////////////////
        protected Int32 DataLengthBits(
			EncodingMode EncodingMode
			)
        {
            // Data length bits
            switch(EncodingMode)
            {
            // numeric mode
            case EncodingMode.Numeric:
                return(Version < 10 ? 10 : (Version < 27 ? 12 : 14));

            // alpha numeric mode
            case EncodingMode.AlphaNumeric:
                return(Version < 10 ? 9 : (Version < 27 ? 11 : 13));

            // byte mode
            case EncodingMode.Byte:
                return(Version < 10 ? 8 : 16);
            }
            throw new ApplicationException("Encoding mode error");
        }
Пример #43
0
        private void Import(string xmlInfo, string glyphs)
        {
            Bitmap image = (Bitmap)Image.FromFile(glyphs);
            XDocument doc = XDocument.Load(xmlInfo);
            XElement root = doc.Element("NFTR");

            this.MagicStamp = "NFTR";
            this.VersionS   = root.Element("Version").Value;

            this.errorChar    = ushort.Parse(root.Element("ErrorChar").Value);
            this.lineGap      = byte.Parse(root.Element("LineGap").Value);
            this.boxWidth     = byte.Parse(root.Element("BoxWidth").Value);
            this.boxHeight    = byte.Parse(root.Element("BoxHeight").Value);
            this.glyphWidth   = byte.Parse(root.Element("GlyphWidth").Value);
            this.glyphHeight  = byte.Parse(root.Element("GlyphHeight").Value);
            this.depth        = byte.Parse(root.Element("Depth").Value);
            this.defaultWidth = GWidth.FromXml(root.Element("DefaultWidth"));
            this.rotation     = (RotationMode)Enum.Parse(typeof(RotationMode), root.Element("Rotation").Value);
            this.encoding     = (EncodingMode)Enum.Parse(typeof(EncodingMode), root.Element("Encoding").Value);

            // Gets Width regions
            XElement xwidths = root.Element("Widths");
            Cwdh.WidthRegion[] widthRegs = new Cwdh.WidthRegion[xwidths.Elements("Region").Count()];

                // ... gets the data from the xml
            foreach (XElement xreg in xwidths.Elements("Region")) {
                int id = int.Parse(xreg.Element("Id").Value);

                widthRegs[id] = new Cwdh.WidthRegion(this.defaultWidth);
                widthRegs[id].Id = id;
                widthRegs[id].FirstChar = Convert.ToUInt16(xreg.Element("FirstChar").Value, 16);
                widthRegs[id].LastChar  = Convert.ToUInt16(xreg.Element("LastChar").Value,  16);
            }

                // ... assign the next region
            for (int i = 0; i < widthRegs.Length; i++) {
                if (i + 1 == widthRegs.Length)
                    widthRegs[i].NextRegion = null;
                else
                    widthRegs[i].NextRegion = widthRegs[i + 1];
            }

            // Gets Cmap regions
            XElement xcmaps = root.Element("Maps");
            this.cmaps = new Cmap[xcmaps.Elements("Map").Count()];

            foreach (XElement xmap in xcmaps.Elements("Map")) {
                int id = int.Parse(xmap.Element("Id").Value);

                this.cmaps[id] = new Cmap(this);
                this.cmaps[id].Id = id;
                this.cmaps[id].Type      = Convert.ToUInt32(xmap.Element("Type").Value);
                this.cmaps[id].FirstChar = Convert.ToUInt16(xmap.Element("FirstChar").Value, 16);
                this.cmaps[id].LastChar  = Convert.ToUInt16(xmap.Element("LastChar").Value,  16);
            }

            // Gets Glyphs
            XElement xglyphs = root.Element("Glyphs");
            this.glyphs = new List<Glyph>(xglyphs.Elements("Glyph").Count());
            for (int i = 0; i < xglyphs.Elements("Glyph").Count(); i++)
                this.glyphs.Add(new Glyph());

            // Reversing the glyphs, there are more probability to have high char codes first
            // ... so there will be less array resizing in InsertWidth and InsertChar
            foreach (XElement xglyph in xglyphs.Elements("Glyph").Reverse()) {
                int id = int.Parse(xglyph.Element("Id").Value);

                Glyph g = new Glyph();
                g.Id       = id;
                g.Width    = GWidth.FromXml(xglyph.Element("Width"));
                g.Image    = this.CharFromMap(image, id);
                g.IdMap    = int.Parse(xglyph.Element("IdMap").Value);
                g.CharCode = Convert.ToUInt16(xglyph.Element("Code").Value, 16);

                this.glyphs[id] = g;
                if (g.Width.IdRegion >= 0)
                    widthRegs[g.Width.IdRegion].InsertWidth(g.CharCode, g.Width, g.Id);
                this.cmaps[g.IdMap].InsertCharCode(g.Id, g.CharCode);
            }

            this.CreateStructure(widthRegs[0]);
        }
Пример #44
0
        protected override void Read(Stream strIn, int size)
        {
            base.Read(strIn, size);

            this.finf  = this.Blocks.GetByType<Finf>(0);
            this.cglp  = this.Blocks.GetByType<Cglp>(0);
            this.cwdh  = this.Blocks.GetByType<Cwdh>(0);
            this.cmaps = this.Blocks.GetByType<Cmap>().ToArray();

            this.errorChar    = this.finf.ErrorCharIndex;
            this.encoding     = this.finf.Encoding;
            this.lineGap      = this.finf.LineGap;
            this.defaultWidth = this.finf.DefaultWidth;
            this.glyphHeight  = this.cglp.GlyphHeight;
            this.glyphWidth   = this.cglp.GlyphWidth;
            this.boxWidth     = this.cglp.BoxWidth;
            this.boxHeight    = this.cglp.BoxHeight;
            this.depth        = this.cglp.Depth;
            this.rotation     = (RotationMode)this.cglp.Rotation;

            // Get glyphs info
            this.glyphs = new List<Glyph>();
            for (int i = 0, idx = 0; i < this.cglp.NumGlyphs; i++) {
                int idMap;
                ushort charCode = this.SearchCharByImage(i, out idMap);
                if (idMap == -1) {
                    this.cglp.GetGlyphImage(i).Save("Unvalid char " + i.ToString() + ".png");
                    continue;
                }

                Glyph g = new Glyph();
                g.Id       = idx++;
                g.Image    = this.cglp.GetGlyph(i);
                g.Width    = this.cwdh.GetWidth(charCode, g.Id);
                g.CharCode = charCode;
                g.IdMap    = idMap;

                this.glyphs.Add(g);
            }

            #if DEBUG
            this.PrintInfo();
            #endif
        }
Пример #45
0
        ////////////////////////////////////////////////////////////////////
        // Encode input byte array into QRCode boolean matrix
        ////////////////////////////////////////////////////////////////////
        internal Byte[,] EncodeQRCode(
			String[]		SegDataString,
			ErrorCorrection	ErrorCorrection
			)
        {
            // save data string array
            this.SegDataString = SegDataString;
            if(SegDataString == null || SegDataString.Length == 0) throw new ApplicationException("Input data string is null or empty");

            // create encoding mode array
            SegEncodingMode = new EncodingMode[SegDataString.Length];

            // create QR code boolean aray
            return(EncodeQRCode(ErrorCorrection));
        }
 private string PlainTextToBinary(string plainText, EncodingMode encMode, bool utf8Bom)
 {
     if (encMode.Equals(EncodingMode.Numeric))
         return PlainTextToBinaryNumeric(plainText);
     if (encMode.Equals(EncodingMode.Alphanumeric))
         return PlainTextToBinaryAlphanumeric(plainText);
     return encMode.Equals(EncodingMode.Byte) ? PlainTextToBinaryByte(plainText, utf8Bom) : string.Empty;
 }
 private static int GetDataLength(EncodingMode encoding, string plainText, string codedText)
 {
     return IsUtf8(encoding, plainText) ? (codedText.Length / 8) : plainText.Length;
 }
Пример #48
0
  /**
 * Creates an instance and fills the fields based on ... the fields
 */
  public Ole10Native(String label, String filename, String command, byte[] data)
  {
      Label=(label);
      FileName=(filename);
      Command=(command);
      DataBuffer=(data);
      mode = EncodingMode.parsed;
  }