-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathBitWriter.hs
More file actions
358 lines (304 loc) · 13.2 KB
/
BitWriter.hs
File metadata and controls
358 lines (304 loc) · 13.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
-- | This module implement helper functions to read & write data
-- at bits level.
module Codec.Picture.BitWriter( BoolReader
, emptyBoolState
, BoolState
, byteAlignJpg
, getNextBitsLSBFirst
, getNextBitsMSBFirst
, getNextBitJpg
, getNextIntJpg
, setDecodedString
, setDecodedStringMSB
, setDecodedStringJpg
, runBoolReader
, BoolWriteStateRef
, newWriteStateRef
, finalizeBoolWriter
, finalizeBoolWriterGif
, writeBits'
, writeBitsGif
, initBoolState
, initBoolStateJpg
, execBoolReader
, runBoolReaderWith
) where
#if !MIN_VERSION_base(4,8,0)
import Control.Applicative( (<*>), (<$>) )
#endif
import Data.STRef
import Control.Monad( when )
import Control.Monad.ST( ST )
import qualified Control.Monad.Trans.State.Strict as S
import Data.Int ( Int32 )
import Data.Word( Word8, Word32 )
import Data.Bits( (.&.), (.|.), unsafeShiftR, unsafeShiftL )
import Codec.Picture.VectorByteConversion( blitVector )
import qualified Data.Vector.Storable.Mutable as M
import qualified Data.Vector.Storable as VS
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as L
--------------------------------------------------
---- Reader
--------------------------------------------------
-- | Current bit index, current value, string
data BoolState = BoolState {-# UNPACK #-} !Int
{-# UNPACK #-} !Word8
!B.ByteString
emptyBoolState :: BoolState
emptyBoolState = BoolState (-1) 0 B.empty
-- | Type used to read bits
type BoolReader s a = S.StateT BoolState (ST s) a
runBoolReader :: BoolReader s a -> ST s a
runBoolReader action = S.evalStateT action $ BoolState 0 0 B.empty
runBoolReaderWith :: BoolState -> BoolReader s a -> ST s (a, BoolState)
runBoolReaderWith st action = S.runStateT action st
execBoolReader :: BoolState -> BoolReader s a -> ST s BoolState
execBoolReader st reader = S.execStateT reader st
initBoolState :: B.ByteString -> BoolState
initBoolState str = case B.uncons str of
Nothing -> BoolState 0 0 B.empty
Just (v, rest) -> BoolState 0 v rest
initBoolStateJpg :: B.ByteString -> BoolState
initBoolStateJpg str =
case B.uncons str of
Nothing -> BoolState 0 0 B.empty
Just (0xFF, rest) -> case B.uncons rest of
Nothing -> BoolState 7 0 B.empty
Just (0x00, afterMarker) -> BoolState 7 0xFF afterMarker
Just (_ , afterMarker) -> initBoolStateJpg afterMarker
Just (v, rest) -> BoolState 7 v rest
-- | Bitify a list of things to decode.
setDecodedString :: B.ByteString -> BoolReader s ()
setDecodedString str = case B.uncons str of
Nothing -> S.put $ BoolState 0 0 B.empty
Just (v, rest) -> S.put $ BoolState 0 v rest
-- | Drop all bit until the bit of indice 0, useful to parse restart
-- marker, as they are byte aligned, but Huffman might not.
byteAlignJpg :: BoolReader s ()
byteAlignJpg = do
BoolState idx _ chain <- S.get
when (idx /= 7) (setDecodedStringJpg chain)
getNextBitJpg :: BoolReader s Bool
{-# INLINE getNextBitJpg #-}
getNextBitJpg = do
BoolState idx v chain <- S.get
let val = (v .&. (1 `unsafeShiftL` idx)) /= 0
if idx == 0
then setDecodedStringJpg chain
else S.put $ BoolState (idx - 1) v chain
return val
getNextIntJpg :: Int -> BoolReader s Int32
{-# INLINE getNextIntJpg #-}
getNextIntJpg = go 0 where
go !acc !0 = return acc
go !acc !n = do
BoolState idx v chain <- S.get
let !leftBits = 1 + fromIntegral idx
if n >= leftBits then do
setDecodedStringJpg chain
let !remaining = n - leftBits
!mask = (1 `unsafeShiftL` leftBits) - 1
!finalV = fromIntegral v .&. mask
!theseBits = finalV `unsafeShiftL` remaining
go (acc .|. theseBits) remaining
else do
let !remaining = leftBits - n
!mask = (1 `unsafeShiftL` n) - 1
!finalV = fromIntegral v `unsafeShiftR` remaining
S.put $ BoolState (fromIntegral remaining - 1) v chain
return $ (finalV .&. mask) .|. acc
setDecodedStringMSB :: B.ByteString -> BoolReader s ()
setDecodedStringMSB str = case B.uncons str of
Nothing -> S.put $ BoolState 8 0 B.empty
Just (v, rest) -> S.put $ BoolState 8 v rest
{-# INLINE getNextBitsMSBFirst #-}
getNextBitsMSBFirst :: Int -> BoolReader s Word32
getNextBitsMSBFirst requested = go 0 requested where
go :: Word32 -> Int -> BoolReader s Word32
go !acc !0 = return acc
go !acc !n = do
BoolState idx v chain <- S.get
let !leftBits = fromIntegral idx
if n >= leftBits then do
setDecodedStringMSB chain
let !theseBits = fromIntegral v `unsafeShiftL` (n - leftBits)
go (acc .|. theseBits) (n - leftBits)
else do
let !remaining = leftBits - n
!mask = (1 `unsafeShiftL` remaining) - 1
S.put $ BoolState (fromIntegral remaining) (v .&. mask) chain
return $ (fromIntegral v `unsafeShiftR` remaining) .|. acc
{-# INLINE getNextBitsLSBFirst #-}
getNextBitsLSBFirst :: Int -> BoolReader s Word32
getNextBitsLSBFirst count = aux 0 count
where aux acc 0 = return acc
aux acc n = do
bit <- getNextBit
let nextVal | bit = acc .|. (1 `unsafeShiftL` (count - n))
| otherwise = acc
aux nextVal (n - 1)
{-# INLINE getNextBit #-}
getNextBit :: BoolReader s Bool
getNextBit = do
BoolState idx v chain <- S.get
let val = (v .&. (1 `unsafeShiftL` idx)) /= 0
if idx == 7
then setDecodedString chain
else S.put $ BoolState (idx + 1) v chain
return val
-- | Bitify a list of things to decode. Handle Jpeg escape
-- code (0xFF 0x00), thus should be only used in JPEG decoding.
setDecodedStringJpg :: B.ByteString -> BoolReader s ()
setDecodedStringJpg str = case B.uncons str of
Nothing -> S.put $ BoolState 7 0 B.empty
Just (0xFF, rest) -> case B.uncons rest of
Nothing -> S.put $ BoolState 7 0 B.empty
Just (0x00, afterMarker) -> -- trace "00" $
S.put $ BoolState 7 0xFF afterMarker
Just (_ , afterMarker) -> setDecodedStringJpg afterMarker
Just (v, rest) ->
S.put $ BoolState 7 v rest
--------------------------------------------------
---- Writer
--------------------------------------------------
defaultBufferSize :: Int
defaultBufferSize = 256 * 1024
data BoolWriteStateRef s = BoolWriteStateRef
{ bwsCurrBuffer :: STRef s (M.MVector s Word8)
, bwsBufferList :: STRef s [B.ByteString]
, bwsWrittenWords :: STRef s Int
, bwsBitAcc :: STRef s Word8
, bwsBitReaded :: STRef s Int
}
newWriteStateRef :: ST s (BoolWriteStateRef s)
newWriteStateRef = do
origMv <- M.new defaultBufferSize
BoolWriteStateRef <$> newSTRef origMv
<*> newSTRef []
<*> newSTRef 0
<*> newSTRef 0
<*> newSTRef 0
finalizeBoolWriter :: BoolWriteStateRef s -> ST s L.ByteString
finalizeBoolWriter st = do
flushLeftBits' st
forceBufferFlushing' st
L.fromChunks <$> readSTRef (bwsBufferList st)
forceBufferFlushing' :: BoolWriteStateRef s -> ST s ()
forceBufferFlushing' (BoolWriteStateRef { bwsCurrBuffer = vecRef
, bwsWrittenWords = countRef
, bwsBufferList = lstRef
}) = do
vec <- readSTRef vecRef
count <- readSTRef countRef
lst <- readSTRef lstRef
nmv <- M.new defaultBufferSize
str <- byteStringFromVector vec count
writeSTRef vecRef nmv
writeSTRef lstRef $ lst ++ [str]
writeSTRef countRef 0
flushCurrentBuffer' :: BoolWriteStateRef s -> ST s ()
flushCurrentBuffer' st = do
count <- readSTRef $ bwsWrittenWords st
when (count >= defaultBufferSize)
(forceBufferFlushing' st)
byteStringFromVector :: M.MVector s Word8 -> Int -> ST s B.ByteString
byteStringFromVector vec size = do
frozen <- VS.unsafeFreeze vec
return $ blitVector frozen 0 size
setBitCount' :: BoolWriteStateRef s -> Word8 -> Int -> ST s ()
{-# INLINE setBitCount' #-}
setBitCount' st acc count = do
writeSTRef (bwsBitAcc st) acc
writeSTRef (bwsBitReaded st) count
resetBitCount' :: BoolWriteStateRef s -> ST s ()
{-# INLINE resetBitCount' #-}
resetBitCount' st = setBitCount' st 0 0
pushByte' :: BoolWriteStateRef s -> Word8 -> ST s ()
{-# INLINE pushByte' #-}
pushByte' st v = do
flushCurrentBuffer' st
idx <- readSTRef (bwsWrittenWords st)
vec <- readSTRef (bwsCurrBuffer st)
M.write vec idx v
writeSTRef (bwsWrittenWords st) $ idx + 1
flushLeftBits' :: BoolWriteStateRef s -> ST s ()
flushLeftBits' st = do
currCount <- readSTRef $ bwsBitReaded st
when (currCount > 0) $ do
currWord <- readSTRef $ bwsBitAcc st
pushByte' st $ currWord `unsafeShiftL` (8 - currCount)
-- | Append some data bits to a Put monad.
writeBits' :: BoolWriteStateRef s
-> Word32 -- ^ The real data to be stored. Actual data should be in the LSB
-> Int -- ^ Number of bit to write from 1 to 32
-> ST s ()
{-# INLINE writeBits' #-}
writeBits' st d c = do
currWord <- readSTRef $ bwsBitAcc st
currCount <- readSTRef $ bwsBitReaded st
serialize d c currWord currCount
where dumpByte 0xFF = pushByte' st 0xFF >> pushByte' st 0x00
dumpByte i = pushByte' st i
serialize bitData bitCount currentWord count
| bitCount + count == 8 = do
resetBitCount' st
dumpByte (fromIntegral $ (currentWord `unsafeShiftL` bitCount) .|.
fromIntegral cleanData)
| bitCount + count < 8 =
let newVal = currentWord `unsafeShiftL` bitCount
in setBitCount' st (newVal .|. fromIntegral cleanData) $ count + bitCount
| otherwise =
let leftBitCount = 8 - count :: Int
highPart = cleanData `unsafeShiftR` (bitCount - leftBitCount) :: Word32
prevPart = fromIntegral currentWord `unsafeShiftL` leftBitCount :: Word32
nextMask = (1 `unsafeShiftL` (bitCount - leftBitCount)) - 1 :: Word32
newData = cleanData .&. nextMask :: Word32
newCount = bitCount - leftBitCount :: Int
toWrite = fromIntegral $ prevPart .|. highPart :: Word8
in dumpByte toWrite >> serialize newData newCount 0 0
where cleanMask = (1 `unsafeShiftL` bitCount) - 1 :: Word32
cleanData = bitData .&. cleanMask :: Word32
-- | Append some data bits to a Put monad.
writeBitsGif :: BoolWriteStateRef s
-> Word32 -- ^ The real data to be stored. Actual data should be in the LSB
-> Int -- ^ Number of bit to write from 1 to 32
-> ST s ()
{-# INLINE writeBitsGif #-}
writeBitsGif st d c = do
currWord <- readSTRef $ bwsBitAcc st
currCount <- readSTRef $ bwsBitReaded st
serialize d c currWord currCount
where dumpByte = pushByte' st
serialize bitData bitCount currentWord count
| bitCount + count == 8 = do
resetBitCount' st
dumpByte (fromIntegral $ currentWord .|.
(fromIntegral cleanData `unsafeShiftL` count))
| bitCount + count < 8 =
let newVal = fromIntegral cleanData `unsafeShiftL` count
in setBitCount' st (newVal .|. currentWord) $ count + bitCount
| otherwise =
let leftBitCount = 8 - count :: Int
newData = cleanData `unsafeShiftR` leftBitCount :: Word32
newCount = bitCount - leftBitCount :: Int
toWrite = fromIntegral $ fromIntegral currentWord
.|. (cleanData `unsafeShiftL` count) :: Word8
in dumpByte toWrite >> serialize newData newCount 0 0
where cleanMask = (1 `unsafeShiftL` bitCount) - 1 :: Word32
cleanData = bitData .&. cleanMask :: Word32
finalizeBoolWriterGif :: BoolWriteStateRef s -> ST s L.ByteString
finalizeBoolWriterGif st = do
flushLeftBitsGif st
forceBufferFlushing' st
L.fromChunks <$> readSTRef (bwsBufferList st)
flushLeftBitsGif :: BoolWriteStateRef s -> ST s ()
flushLeftBitsGif st = do
currCount <- readSTRef $ bwsBitReaded st
when (currCount > 0) $ do
currWord <- readSTRef $ bwsBitAcc st
pushByte' st currWord
{-# ANN module "HLint: ignore Reduce duplication" #-}