Moin,
habe ihn nur kurz getestet, hoffentlich ist er halbwegs robust. Ich dachte mir schon länger: Bei all unseren lustigen Abenteuern waren wir immer mit Huffman unterwegs. Daher hier eine (langsame) Alternative. Ziel war es nicht so schnell wie möglich zu sein, sondern "so einfach wie möglich". Was mich nämlich sehr an sämtlichen Versionen die man online finden kann stört ist die unnötige Komplexität und die unnötigen Einschränkungen (funktioniert nur "manchmal", oder "ich rechne mit float/double", oder "der Output ist im Dezimalsystem", oder "man muss char8 als Datentyp nehmen", oder "die interne Bitrate kann zu klein sein/unkontrolliert explodieren, bitte verwende BigInt", oder "man muss nach dem EOF noch ein paar mehr Zahlen mitschicken weil der Decoder sonst danebenschießt", oder oder oder).
; ------ dec2bin UDF stuff ------
Global $__I2A[256], $__I2B[256], $__I2C[11111112]
Global $__I2I = DllStructCreate('int64 v')
Global $__I28 = DllStructCreate('byte a;byte b; byte c; byte d; byte e; byte f; byte g; byte h;', DllStructGetPtr($__I2I))
__I2B_START()
; -----------------------------
Global $sin = StringToASCIIArray('Hallo, ich bin ein Teststring um zu testen ob es klappt. This is a test.', Default, Default, 1)
Global $tab = OptimalTable($sin)
Func OptimalTable($a) ; nur für statisch optimal. Das ist kein predictor!
Local $iMax = $a[0]
For $i = 0 To UBound($a) - 1
If $a[$i] > $iMax Then $iMax = $a[$i]
Next
Local $_[], $c = 0
For $i = 0 To $iMax
$c = 0
For $j = 0 To UBound($a) - 1
If $a[$j] = $i Then $c += 1
Next
$_[$i] = $c
Next
Return $_
EndFunc
__Print($sin)
ConsoleWrite('Str['&UBound($sin)&']: ' & StringFromASCIIArray($sin) & @CRLF & @CRLF)
Global $enc = Encode($sin, $tab)
ConsoleWrite('Bin[' & StringLen($enc) & ']: ' & $enc & @CRLF)
ConsoleWrite('Bit/Symbol: ' & StringFormat('%5.3f', StringLen($enc) / UBound($sin)) & @CRLF & @CRLF)
Global $out = Decode($enc, $tab)
__Print($out)
ConsoleWrite('Str['&UBound($out)&']: ' & StringFromASCIIArray(__ToArray($out)) & @CRLF & @CRLF)
If UBound($sin) <> UBound($out) Then
ConsoleWrite('ERROR: Length is not equal: in[' & UBound($sin) & '] != out [' & UBound($out) & ']' & @CRLF)
Else
For $i = 0 To UBound($sin) - 1
If $sin[$i] <> $out[$i] Then ConsoleWrite('ERROR: Symbol ' & $i & ': in(' & $sin[$i] & ') != out(' & $out[$i] & ')' & @CRLF)
Next
EndIf
; $sBits (string of '0' and '1')
; $mProbabilities[num symbols] (Array or Map of float or int) - normalized or not does not matter. 0 is allowed.
; returns $mSymbolsOut (Array or Map of int)
Func Decode($sBits, $mProbabilities)
If Not IsMap($mProbabilities) Then $mProbabilities = __ToMap($mProbabilities)
; Minimal internal bitrate
; should be big enough so small probabilities get represented accurately
; should be small enough so that the effective internal bitrate stays below 31 bit.
; is by definition capped at 2x $iBitrate, so having it at 15 cannot overshoot 30 bit internally.
Local $iBitrate = 15, $iHighestValue = Int(2 ^ $iBitrate - 1, 1)
Local $EOF_SYMBOL = __AddEOF(0, $mProbabilities) ; adds EOF at the end
__PadZero($sBits, $iBitrate * 2) ; adds some zeros at the end
Local $iCurrentBitrate = $iBitrate
Local $mSymbolsOut[], $iSymbol = 0, $mDiscreteProb[]
Local $sSearchLow = '', $iSearchMid = 0, $sSearchHigh = ''
Local $iWindowLow = 0, $iWindowHigh = $iHighestValue, $iWindowSizeU = $iWindowHigh - $iWindowLow + 1
; Stop at 1MiB for now. Just to be safe.
For $iSafeIter = 0 To 1024 * 1024 - 1
; search some number within the discrete probabilities
$iSearchMid = _BinToDec(StringLeft($sBits, $iCurrentBitrate))
$mDiscreteProb = __DiscreteProbabilityPrefixScan($mProbabilities, $iWindowSizeU)
; Find symbol where $iSearchMid hits the probability region
$iSymbol = -1
For $i = 0 To UBound($mDiscreteProb) - 2 ; linear search -> slow but easy to understand
If $iSearchMid <= $mDiscreteProb[$i + 1] + $iWindowLow - 1 Then
$iSymbol = $i
ExitLoop
EndIf
Next
; Should not happen. Something went wrong.
If $iSymbol = -1 Then
ConsoleWrite('ERROR: Cannot find Symbol for ' & _DecToBinL($iSearchMid, $iCurrentBitrate) & @CRLF)
Return $mSymbolsOut
EndIf
; Check if the symbol was EOF
If $iSymbol = $EOF_SYMBOL Then ExitLoop
MapAppend($mSymbolsOut, $iSymbol)
; Get search region for the decoded symbol to update bitrate and window
$sSearchLow = _DecToBinL($mDiscreteProb[$iSymbol] + $iWindowLow, $iCurrentBitrate)
$sSearchHigh = _DecToBinL($mDiscreteProb[$iSymbol + 1] + $iWindowLow - 1, $iCurrentBitrate)
; Remove bits from the left that were consumed by the current symbol
$sBits = StringTrimLeft($sBits, StringLen(__PopStringEq($sSearchLow, $sSearchHigh)))
; Update range bitrate and current bitrate
$iCurrentBitrate = __FillBits($sSearchLow, $sSearchHigh, $iHighestValue)
; Update current window
$iWindowLow = _BinToDec($sSearchLow)
$iWindowHigh = _BinToDec($sSearchHigh)
$iWindowSizeU = $iWindowHigh - $iWindowLow + 1
Next
Return $mSymbolsOut
EndFunc
; $mSymbolsIn[input len] (Array or Map of int)
; $mProbabilities[num symbols] (Array or Map of float or int) - normalized or not does not matter. 0 is allowed.
; returns string of 0 or 1
Func Encode($mSymbolsIn, $mProbabilities, $bDebug = True)
If Not IsMap($mSymbolsIn) Then $mSymbolsIn = __ToMap($mSymbolsIn)
If Not IsMap($mProbabilities) Then $mProbabilities = __ToMap($mProbabilities)
; Minimal internal bitrate
; should be big enough so small probabilities get represented accurately
; should be small enough so that the effective internal bitrate stays below 31 bit.
; is by definition capped at 2x $iBitrate, so having it at 15 cannot overshoot 30 bit internally.
Local $iBitrate = 15, $iHighestValue = Int(2 ^ $iBitrate - 1, 1)
Local $EOF_SYMBOL = __AddEOF($mSymbolsIn, $mProbabilities)
Local $sBitsOut = '', $sBitsDebug = '', $sTmp = ''
Local $sSearchLow = '', $sSearchHigh = ''
Local $iWindowLow = 0, $iWindowHigh = $iHighestValue, $iWindowSizeU = $iWindowHigh - $iWindowLow + 1
Local $iCurrentBitrate = $iBitrate, $iSymbol = 0, $mDiscreteProb[]
For $i = 0 To UBound($mSymbolsIn) - 1
; the symbol corresponds to some range within the discrete probabilities
$iSymbol = $mSymbolsIn[$i]
$mDiscreteProb = __DiscreteProbabilityPrefixScan($mProbabilities, $iWindowSizeU)
; the range (inclusive)
$sSearchLow = _DecToBinL($mDiscreteProb[$iSymbol] + $iWindowLow, $iCurrentBitrate)
$sSearchHigh = _DecToBinL($mDiscreteProb[$iSymbol + 1] + $iWindowLow - 1, $iCurrentBitrate)
; append the bits that are equal for the whole range
$sBitsOut &= __PopStringEq($sSearchLow, $sSearchHigh)
; update range bitrate and current bitrate
$iCurrentBitrate = __FillBits($sSearchLow, $sSearchHigh, $iHighestValue)
; update window
$iWindowLow = _BinToDec($sSearchLow)
$iWindowHigh = _BinToDec($sSearchHigh)
$iWindowSizeU = $iWindowHigh - $iWindowLow + 1
Next
; If EOF has a discrete probability of exactly 1, then $iWindowLow is by definition a lot of zeros '00000000000'
; the decoder knows that and therefore wont need additional bits because it can safely fill with zeros
; $sBitsOut &= '|||' & _DecToBinL($iWindowLow, $iCurrentBitrate)
Return $sBitsOut
EndFunc
; $mProbabilities[numSymbols] (array or map of float or int) - normalized or not does not matter. 0 is allowed.
; $iInclusiveRange (int) - total range of valid values
; returns: (map of int) discrete integer prefixes that represent the probabilities
Func __DiscreteProbabilityPrefixScan($mProbabilities, $iInclusiveRange)
Local $n = UBound($mProbabilities), $p[], $q[], $s = 0, $r = 0
$p[0] = 0
$q[0] = 0
For $i = 1 To $n
$p[$i] = $mProbabilities[$i - 1] * $iInclusiveRange
If $p[$i] < 1 Then $p[$i] = 1 ; if input contains values that are too small for the given range
$s += $p[$i]
Next
For $i = 1 To $n
$p[$i] *= ($iInclusiveRange / $s)
If $p[$i] < 1 Then $p[$i] = 1 ; if there are values too small after normalization
$q[$i] = Round($p[$i])
$r += $q[$i]
Next
$r = $iInclusiveRange - $r
If Not $r Then
For $i = 1 To $n
$q[$i] += $q[$i - 1]
Next
Return $q
EndIf
; Add $r in increments to q[i] where it hurts the least. Not 100% perfect because
; the previous step rounds -> does not consider relative error but only absolute error
; and corrections are one sided (increment is constant throughout iterations)
Local $iBest, $dBest, $inc = ($r > 0 ? 1 : -1), $d
For $_ = 1 To Abs($r)
$iBest = 0
$dBest = 1e99
For $i = 1 To $n
If $q[$i] <= 1 And $inc < 0 Then ContinueLoop
$d = (2 * ($q[$i] - $p[$i]) + $inc) / ($p[$i] ^ 2)
If $d < $dBest Then
$dBest = $d
$iBest = $i
EndIf
Next
If Not $iBest Then
ConsoleWrite('ERROR: Could not find a nice element :/' & @CRLF)
Return
EndIf
$q[$iBest] += $inc
Next
For $i = 1 To $n
$q[$i] += $q[$i - 1]
Next
Return $q
EndFunc
; Fills $sSearchLow with trailing zeros and $sSearchHigh with trailing ones until the range is big enough
; returns bitrate required for the resulting numbers
Func __FillBits(ByRef $sSearchLow, ByRef $sSearchHigh, $iRange)
While _BinToDec($sSearchHigh) - _BinToDec($sSearchLow) < $iRange
$sSearchLow &= '0'
$sSearchHigh &= '1'
WEnd
Return StringLen($sSearchLow)
EndFunc
; Removes all leading symbols from $sSearchLow and $sSearchHigh and returns them
Func __PopStringEq(ByRef $sSearchLow, ByRef $sSearchHigh)
Local $sEq = ''
While StringLen($sSearchLow) And (StringLeft($sSearchLow, 1) = StringLeft($sSearchHigh, 1))
$sEq &= StringLeft($sSearchLow, 1)
$sSearchLow = StringTrimLeft($sSearchLow, 1)
$sSearchHigh = StringTrimLeft($sSearchHigh, 1)
WEnd
Return $sEq
EndFunc
; fills $sBits with zeros at the end
Func __PadZero(ByRef $sBits, $iBitrate)
$sBits &= StringLeft('0000000000000000000000000000000000000000000000000000000000000000', $iBitrate)
EndFunc
; $mSymbols (map of int)
; $mProbabilities (map of int or float)
Func __AddEOF(ByRef $mSymbols, ByRef $mProbabilities)
Local $EOF_SYMBOL = UBound($mProbabilities)
MapAppend($mProbabilities, 0) ; Probability 0 EOF-Symbol -> gets a discrete length of exactly one.
If IsMap($mSymbols) Then MapAppend($mSymbols, $EOF_SYMBOL)
Return $EOF_SYMBOL
EndFunc
Func __Print($a)
Local $s
For $i = 0 To UBound($a) - 1
$s &= $a[$i] & ', '
Next
ConsoleWrite(StringTrimRight($s, 2) & @CRLF)
EndFunc
Func __ToArray($m)
Local $n = UBound($m), $a[$n]
For $i = 0 To $n - 1
$a[$i] = $m[$i]
Next
Return $a
EndFunc
Func __ToMap($a)
Local $n = UBound($a), $m[]
For $i = 0 To $n - 1
$m[$i] = $a[$i]
Next
Return $m
EndFunc
; ------ dec2bin UDF stuff ------
Func _BinCap8($sBin, $bRemoveCap = False)
Local Static $aLeft[8] = ['00000000', '0000001', '000001', '00001', '0001', '001', '01', '1']
If Not $bRemoveCap Then Return $aLeft[Mod(StringLen($sBin), 8)] & $sBin
For $i = 0 To 7 Step 1
If StringLeft($sBin, StringLen($aLeft[$i])) = $aLeft[$i] Then Return StringTrimLeft($sBin, StringLen($aLeft[$i]))
Next
EndFunc ;==>BinCap8
Func _DecToBinL($d, $l)
$__I2I.v = $d
Return StringRight($__I2B[$__I28.h] & $__I2B[$__I28.g] & $__I2B[$__I28.f] & $__I2B[$__I28.e] & $__I2B[$__I28.d] & $__I2B[$__I28.c] & $__I2B[$__I28.b] & $__I2B[$__I28.a], $l)
EndFunc ;==>_DecToBin
Func _BinToDec($s)
Local $l = StringLen($s)
Return $l < 9 ? $__I2C[$s] : $l < 17 ? $__I2C[StringTrimRight($s, 8)] * 256 + $__I2C[StringRight($s, 8)] : $l < 25 ? _
$__I2C[StringTrimRight($s, 16)] * 65536 + $__I2C[StringRight(StringTrimRight($s, 8), 8)] * 256 + $__I2C[StringRight( _
$s, 8)] : BitShift($__I2C[StringTrimRight($s, 24)], -24) + $__I2C[StringRight(StringTrimRight($s, 16), 8)] * 65536 _
+ $__I2C[StringRight(StringTrimRight($s, 8), 8)] * 256 + $__I2C[StringRight($s, 8)]
EndFunc ;==>_BinToDec
Func __I2B_START()
Local Static $bReady = False
If $bReady Then Return
Local $t = DllStructCreate('char[64]'), $p = _
DllStructGetPtr($t), $hDll = DllOpen('msvcrt.dll')
For $i = 0 To 255 Step 1
DllCall($hDll, 'ptr:cdecl', '_i64toa', 'int64', _
$i, 'ptr', $p, 'int', 2)
$__I2A[$i] = DllStructGetData($t, 1)
$__I2B[$i] = StringRight('0000000' & $__I2A[$i], 8)
$__I2C[$__I2A[$i]] = $i
Next
DllClose($hDll)
$bReady = True
EndFunc
; -------------------------------
Alles anzeigen
Beispieloutput:
98, 108, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97
Str[79]: blaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
Bin[31]: 1111110010100111110010011100111
Bit/Symbol: 0.392
98, 108, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97
Str[79]: blaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
72, 97, 108, 108, 111, 44, 32, 105, 99, 104, 32, 98, 105, 110, 32, 101, 105, 110, 32, 84, 101, 115, 116, 115, 116, 114, 105, 110, 103, 32, 117, 109, 32, 122, 117, 32, 116, 101, 115, 116, 101, 110, 32, 111, 98, 32, 101, 115, 32, 107, 108, 97, 112, 112, 116, 46, 32, 84, 104, 105, 115, 32, 105, 115, 32, 97, 32, 116, 101, 115, 116, 46
Str[72]: Hallo, ich bin ein Teststring um zu testen ob es klappt. This is a test.
Bin[305]: 00111101010010011011010101110110101010101000011101001101011010101110001011011010010011011101000111101000100011110010001100111011111010011011001010001110100101101001100010110001101100000100101100011101110000011110011000100100010011010100011111000001110001011111001001000101000011101000101111110110110011111
Bit/Symbol: 4.236
72, 97, 108, 108, 111, 44, 32, 105, 99, 104, 32, 98, 105, 110, 32, 101, 105, 110, 32, 84, 101, 115, 116, 115, 116, 114, 105, 110, 103, 32, 117, 109, 32, 122, 117, 32, 116, 101, 115, 116, 101, 110, 32, 111, 98, 32, 101, 115, 32, 107, 108, 97, 112, 112, 116, 46, 32, 84, 104, 105, 115, 32, 105, 115, 32, 97, 32, 116, 101, 115, 116, 46
Str[72]: Hallo, ich bin ein Teststring um zu testen ob es klappt. This is a test.
lg
M