]> gitweb.factorcode.org Git - factor.git/blob - basis/images/jpeg/jpeg.factor
Better error images for non-baseline JPEGs.
[factor.git] / basis / images / jpeg / jpeg.factor
1 ! Copyright (C) 2009 Marc Fauconneau.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: accessors arrays byte-arrays combinators
4 grouping compression.huffman images
5 images.processing io io.binary io.encodings.binary io.files
6 io.streams.byte-array kernel locals math math.bitwise
7 math.constants math.functions math.matrices math.order
8 math.ranges math.vectors memoize multiline namespaces
9 sequences sequences.deep images.loader io.streams.limited ;
10 IN: images.jpeg
11
12 QUALIFIED-WITH: bitstreams bs
13
14 TUPLE: jpeg-image < image
15     { headers }
16     { bitstream }
17     { color-info initial: { f f f f } }
18     { quant-tables initial: { f f } }
19     { huff-tables initial: { f f f f } }
20     { components } ;
21
22 "jpg" jpeg-image register-image-class
23 "jpeg" jpeg-image register-image-class
24
25 <PRIVATE
26
27 : <jpeg-image> ( headers bitstream -- image )
28     jpeg-image new swap >>bitstream swap >>headers ;
29
30 SINGLETONS: SOF DHT DAC RST SOI EOI SOS DQT DNL DRI DHP EXP
31 APP JPG COM TEM RES ;
32
33 ! ISO/IEC 10918-1 Table B.1
34 :: >marker ( byte -- marker )
35     byte
36     {
37       { [ dup HEX: CC = ] [ { DAC } ] }
38       { [ dup HEX: C4 = ] [ { DHT } ] }
39       { [ dup HEX: C9 = ] [ { JPG } ] }
40       { [ dup -4 shift HEX: C = ] [ SOF byte 4 bits 2array ] }
41
42       { [ dup HEX: D8 = ] [ { SOI } ] }
43       { [ dup HEX: D9 = ] [ { EOI } ] }
44       { [ dup HEX: DA = ] [ { SOS } ] }
45       { [ dup HEX: DB = ] [ { DQT } ] }
46       { [ dup HEX: DC = ] [ { DNL } ] }
47       { [ dup HEX: DD = ] [ { DRI } ] }
48       { [ dup HEX: DE = ] [ { DHP } ] }
49       { [ dup HEX: DF = ] [ { EXP } ] }
50       { [ dup -4 shift HEX: D = ] [ RST byte 4 bits 2array ] }
51
52       { [ dup -4 shift HEX: E = ] [ APP byte 4 bits 2array ] }
53       { [ dup HEX: FE = ] [ { COM } ] }
54       { [ dup -4 shift HEX: F = ] [ JPG byte 4 bits 2array ] }
55
56       { [ dup HEX: 01 = ] [ { TEM } ] }
57       [ { RES } ]
58     }
59     cond nip ;
60
61 TUPLE: jpeg-chunk length type data ;
62
63 : <jpeg-chunk> ( type length data -- jpeg-chunk )
64     jpeg-chunk new
65         swap >>data
66         swap >>length
67         swap >>type ;
68
69 TUPLE: jpeg-color-info
70     h v quant-table dc-huff-table ac-huff-table { diff initial: 0 } id ;
71
72 : <jpeg-color-info> ( h v quant-table -- jpeg-color-info )
73     jpeg-color-info new
74         swap >>quant-table
75         swap >>v
76         swap >>h ;
77
78 : jpeg> ( -- jpeg-image ) jpeg-image get ;
79
80 : apply-diff ( dc color -- dc' )
81     [ diff>> + dup ] [ (>>diff) ] bi ;
82
83 : fetch-tables ( component -- )
84     [ [ jpeg> quant-tables>> nth ] change-quant-table drop ]
85     [ [ jpeg> huff-tables>> nth ] change-dc-huff-table drop ]
86     [ [ 2 + jpeg> huff-tables>> nth ] change-ac-huff-table drop ] tri ;
87
88 : read4/4 ( -- a b ) read1 16 /mod ;
89
90 ! headers
91
92 : decode-frame ( header -- )
93     data>>
94     binary
95     [
96         read1 8 assert=
97         2 read be>
98         2 read be>
99         swap 2array jpeg> (>>dim)
100         read1
101         [
102             read1 read4/4 read1 <jpeg-color-info>
103             swap [ >>id ] keep jpeg> color-info>> set-nth
104         ] times
105     ] with-byte-reader ;
106
107 : decode-quant-table ( chunk -- )
108     dup data>>
109     binary
110     [
111         length>>
112         2 - 65 /
113         [
114             read4/4 [ 0 assert= ] dip
115             64 read
116             swap jpeg> quant-tables>> set-nth
117         ] times
118     ] with-byte-reader ;
119
120 : decode-huff-table ( chunk -- )
121     data>> [ binary <byte-reader> ] [ length ] bi
122     stream-throws limit
123     [   
124         [ input-stream get [ count>> ] [ limit>> ] bi < ]
125         [
126             read4/4 swap 2 * +
127             16 read
128             dup [ ] [ + ] map-reduce read
129             binary [ [ read [ B{ } ] unless* ] { } map-as ] with-byte-reader
130             swap jpeg> huff-tables>> set-nth
131         ] while
132     ] with-input-stream* ;
133
134 : decode-scan ( chunk -- )
135     data>>
136     binary
137     [
138         read1 [0,b)
139         [   drop
140             read1 jpeg> color-info>> nth clone
141             read1 16 /mod [ >>dc-huff-table ] [ >>ac-huff-table ] bi*
142         ] map jpeg> (>>components)
143         read1 0 assert=
144         read1 63 assert=
145         read1 16 /mod [ 0 assert= ] bi@
146     ] with-byte-reader ;
147
148 : singleton-first ( seq -- elt )
149     [ length 1 assert= ] [ first ] bi ;
150
151 ERROR: not-a-baseline-jpeg-image ;
152
153 : baseline-parse ( -- )
154     jpeg> headers>> [ type>> { SOF 0 } = ] any? [ not-a-baseline-jpeg-image ] unless
155     jpeg> headers>>
156     {
157         [ [ type>> { SOF 0 } = ] filter singleton-first decode-frame ]
158         [ [ type>> { DQT } = ] filter [ decode-quant-table ] each ]
159         [ [ type>> { DHT } = ] filter [ decode-huff-table ] each ]
160         [ [ type>> { SOS } = ] filter singleton-first decode-scan ]
161     } cleave ;
162
163 : parse-marker ( -- marker )
164     read1 HEX: FF assert=
165     read1 >marker ;
166
167 : parse-headers ( -- chunks )
168     [ parse-marker dup { SOS } = not ]
169     [
170         2 read be>
171         dup 2 - read <jpeg-chunk>
172     ] [ produce ] keep dip swap suffix ;
173
174 MEMO: zig-zag ( -- zz )
175     {
176         {  0  1  5  6 14 15 27 28 }
177         {  2  4  7 13 16 26 29 42 }
178         {  3  8 12 17 25 30 41 43 }
179         {  9 11 18 24 31 40 44 53 }
180         { 10 19 23 32 39 45 52 54 }
181         { 20 22 33 38 46 51 55 60 }
182         { 21 34 37 47 50 56 59 61 }
183         { 35 36 48 49 57 58 62 63 }
184     } flatten ;
185
186 MEMO: yuv>bgr-matrix ( -- m )
187     {
188         { 1  2.03211  0       }
189         { 1 -0.39465 -0.58060 }
190         { 1  0        1.13983 }
191     } ;
192
193 : wave ( x u -- n ) swap 2 * 1 + * pi * 16 / cos ;
194
195 :: dct-vect ( u v -- basis )
196     { 8 8 } coord-matrix [ { u v } [ wave ] 2map product ] map^2
197     1 u v [ 0 = [ 2 sqrt / ] when ] bi@ 4 / m*n ;
198
199 MEMO: dct-matrix ( -- m ) 64 [0,b) [ 8 /mod dct-vect flatten ] map ;
200
201 : mb-dim ( component -- dim )  [ h>> ] [ v>> ] bi 2array ;
202
203 ! : blocks ( component -- seq )
204 !    mb-dim ! coord-matrix flip concat [ [ { 2 2 } v* ] [ v+ ] bi* ] with map ;
205
206 : all-macroblocks ( quot: ( mb -- ) -- )
207     [
208         jpeg>
209         [ dim>> 8 v/n ]
210         [ color-info>> sift { 0 0 } [ mb-dim vmax ] reduce v/ ] bi
211         [ ceiling ] map
212         coord-matrix flip concat
213     ]
214     [ each ] bi* ; inline
215
216 : reverse-zigzag ( b -- b' ) zig-zag swap [ nth ] curry map ;
217
218 : idct-factor ( b -- b' ) dct-matrix v.m ;
219
220 USE: math.blas.vectors
221 USE: math.blas.matrices
222
223 MEMO: dct-matrix-blas ( -- m ) dct-matrix >float-blas-matrix ;
224 : V.M ( x A -- x.A ) Mtranspose swap M.V ;
225 : idct-blas ( b -- b' ) >float-blas-vector dct-matrix-blas V.M ;
226
227 : idct ( b -- b' ) idct-factor ;
228
229 :: draw-block ( block x,y color-id jpeg-image -- )
230     block dup length>> sqrt >fixnum group flip
231     dup matrix-dim coord-matrix flip
232     [
233         [ first2 spin nth nth ]
234         [ x,y v+ color-id jpeg-image draw-color ] bi
235     ] with each^2 ;
236
237 : sign-extend ( bits v -- v' )
238     swap [ ] [ 1 - 2^ < ] 2bi
239     [ -1 swap shift 1 + + ] [ drop ] if ;
240
241 : read1-jpeg-dc ( decoder -- dc )
242     [ read1-huff dup ] [ bs>> bs:read ] bi sign-extend ;
243
244 : read1-jpeg-ac ( decoder -- run/ac )
245     [ read1-huff 16 /mod dup ] [ bs>> bs:read ] bi sign-extend 2array ;
246
247 :: decode-block ( color -- pixels )
248     color dc-huff-table>> read1-jpeg-dc color apply-diff
249     64 0 <array> :> coefs
250     0 coefs set-nth
251     0 :> k!
252     [
253         color ac-huff-table>> read1-jpeg-ac
254         [ first 1 + k + k! ] [ second k coefs set-nth ] [ ] tri
255         { 0 0 } = not
256         k 63 < and
257     ] loop
258     coefs color quant-table>> v*
259     reverse-zigzag idct ;
260     
261 :: draw-macroblock-yuv420 ( mb blocks -- )
262     mb { 16 16 } v* :> pos
263     0 blocks nth pos { 0 0 } v+ 0 jpeg> draw-block
264     1 blocks nth pos { 8 0 } v+ 0 jpeg> draw-block
265     2 blocks nth pos { 0 8 } v+ 0 jpeg> draw-block
266     3 blocks nth pos { 8 8 } v+ 0 jpeg> draw-block
267     4 blocks nth 8 group 2 matrix-zoom concat pos 1 jpeg> draw-block
268     5 blocks nth 8 group 2 matrix-zoom concat pos 2 jpeg> draw-block ;
269     
270 :: draw-macroblock-yuv444 ( mb blocks -- )
271     mb { 8 8 } v* :> pos
272     3 iota [ [ blocks nth pos ] [ jpeg> draw-block ] bi ] each ;
273
274 :: draw-macroblock-y ( mb blocks -- )
275     mb { 8 8 } v* :> pos
276     0 blocks nth pos 0 jpeg> draw-block
277     64 0 <array> pos 1 jpeg> draw-block
278     64 0 <array> pos 2 jpeg> draw-block ;
279  
280     ! %fixme: color hack
281  !   color h>> 2 =
282  !   [ 8 group 2 matrix-zoom concat ] unless
283  !   pos { 8 8 } v* color jpeg> draw-block ;
284
285 : decode-macroblock ( -- blocks )
286     jpeg> components>>
287     [
288         [ mb-dim first2 * iota ]
289         [ [ decode-block ] curry replicate ] bi
290     ] map concat ;
291
292 : cleanup-bitstream ( bytes -- bytes' )
293     binary [
294         [
295             { HEX: FF } read-until
296             read1 tuck HEX: 00 = and
297         ]
298         [ drop ] produce
299         swap >marker {  EOI } assert=
300         swap suffix
301         { HEX: FF } join
302     ] with-byte-reader ;
303
304 : setup-bitmap ( image -- )
305     dup dim>> 16 v/n [ ceiling ] map 16 v*n >>dim
306     BGR >>component-order
307     ubyte-components >>component-type
308     f >>upside-down?
309     dup dim>> first2 * 3 * 0 <array> >>bitmap
310     drop ;
311
312 ERROR: unsupported-colorspace ;
313 SINGLETONS: YUV420 YUV444 Y MAGIC! ;
314
315 :: detect-colorspace ( jpeg-image -- csp )
316     jpeg-image color-info>> sift :> colors
317     MAGIC!
318     colors length 1 = [ drop Y ] when
319     colors length 3 =
320     [
321         colors [ mb-dim { 1 1 } = ] all?
322         [ drop YUV444 ] when
323
324         colors unclip
325         [ [ mb-dim { 1 1 } = ] all? ]
326         [ mb-dim { 2 2 } =  ] bi* and
327         [ drop YUV420 ] when
328     ] when ;
329     
330 ! this eats ~50% cpu time
331 : draw-macroblocks ( mbs -- )
332     jpeg> detect-colorspace
333     {
334         { YUV420 [ [ first2 draw-macroblock-yuv420 ] each ] }
335         { YUV444 [ [ first2 draw-macroblock-yuv444 ] each ] }
336         { Y      [ [ first2 draw-macroblock-y ] each ] }
337         [ unsupported-colorspace ]
338     } case ;
339
340 ! this eats ~25% cpu time
341 : color-transform ( yuv -- rgb )
342     { 128 0 0 } v+ yuv>bgr-matrix swap m.v
343     [ 0 max 255 min >fixnum ] map ;
344
345 : baseline-decompress ( -- )
346     jpeg> bitstream>> cleanup-bitstream { 255 255 255 255 } append
347     >byte-array bs:<msb0-bit-reader> jpeg> (>>bitstream)
348     jpeg> 
349     [ bitstream>> ] 
350     [ [ [ <huffman-decoder> ] with map ] change-huff-tables drop ] bi
351     jpeg> components>> [ fetch-tables ] each
352     [ decode-macroblock 2array ] accumulator 
353     [ all-macroblocks ] dip
354     jpeg> setup-bitmap draw-macroblocks 
355     jpeg> bitmap>> 3 <groups> [ color-transform ] change-each
356     jpeg> [ >byte-array ] change-bitmap drop ;
357
358 ERROR: not-a-jpeg-image ;
359
360 PRIVATE>
361
362 M: jpeg-image stream>image ( stream jpeg-image -- bitmap )
363     drop [
364         parse-marker { SOI } = [ not-a-jpeg-image ] unless
365         parse-headers
366         contents <jpeg-image>
367     ] with-input-stream
368     dup jpeg-image [
369         baseline-parse
370         baseline-decompress
371     ] with-variable ;