]> gitweb.factorcode.org Git - factor.git/blob - extra/images/jpeg/jpeg.factor
factor: trim more using lists.
[factor.git] / extra / 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 compression.huffman endian grouping images images.loader
5 images.processing io io.encodings.binary io.streams.byte-array
6 io.streams.limited io.streams.throwing kernel math math.bitwise
7 math.blas.matrices math.blas.vectors math.constants
8 math.functions math.matrices math.order math.vectors namespaces
9 sequences sequences.deep ;
10 QUALIFIED-WITH: bitstreams bs
11 IN: images.jpeg
12
13 SINGLETON: jpeg-image
14
15 TUPLE: loading-jpeg < image
16     { headers }
17     { bitstream }
18     { color-info initial: { f f f f } }
19     { quant-tables initial: { f f } }
20     { huff-tables initial: { f f f f } }
21     { components } ;
22
23 { "jpg" "jpeg" } [ jpeg-image ?register-image-class ] each
24
25 <PRIVATE
26
27 : <loading-jpeg> ( headers bitstream -- image )
28     loading-jpeg 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 0xCC = ] [ { DAC } ] }
38       { [ dup 0xC4 = ] [ { DHT } ] }
39       { [ dup 0xC9 = ] [ { JPG } ] }
40       { [ dup -4 shift 0xC = ] [ SOF byte 4 bits 2array ] }
41
42       { [ dup 0xD8 = ] [ { SOI } ] }
43       { [ dup 0xD9 = ] [ { EOI } ] }
44       { [ dup 0xDA = ] [ { SOS } ] }
45       { [ dup 0xDB = ] [ { DQT } ] }
46       { [ dup 0xDC = ] [ { DNL } ] }
47       { [ dup 0xDD = ] [ { DRI } ] }
48       { [ dup 0xDE = ] [ { DHP } ] }
49       { [ dup 0xDF = ] [ { EXP } ] }
50       { [ dup -4 shift 0xD = ] [ RST byte 4 bits 2array ] }
51
52       { [ dup -4 shift 0xE = ] [ APP byte 4 bits 2array ] }
53       { [ dup 0xFE = ] [ { COM } ] }
54       { [ dup -4 shift 0xF = ] [ JPG byte 4 bits 2array ] }
55
56       { [ dup 0x01 = ] [ { 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 limit-stream [
122         [ input-stream get stream>> [ count>> ] [ limit>> ] bi < ]
123         [
124             read4/4 swap 2 * +
125             16 read
126             dup [ ] [ + ] map-reduce read
127             binary [ [ read [ B{ } ] unless* ] { } map-as ] with-byte-reader
128             swap jpeg> huff-tables>> set-nth
129         ] while
130     ] stream-throw-on-eof ;
131
132 : decode-scan ( chunk -- )
133     data>>
134     binary
135     [
136         read1 <iota>
137         [   drop
138             read1 jpeg> color-info>> nth clone
139             read1 16 /mod [ >>dc-huff-table ] [ >>ac-huff-table ] bi*
140         ] map jpeg> components<<
141         read1 0 assert=
142         read1 63 assert=
143         read1 16 /mod [ 0 assert= ] bi@
144     ] with-byte-reader ;
145
146 : singleton-first ( seq -- elt )
147     [ length 1 assert= ] [ first ] bi ;
148
149 ERROR: not-a-baseline-jpeg-image ;
150
151 : baseline-parse ( -- )
152     jpeg> headers>> [ type>> { SOF 0 } = ] any? [ not-a-baseline-jpeg-image ] unless
153     jpeg> headers>>
154     {
155         [ [ type>> { SOF 0 } = ] filter singleton-first decode-frame ]
156         [ [ type>> { DQT } = ] filter [ decode-quant-table ] each ]
157         [ [ type>> { DHT } = ] filter [ decode-huff-table ] each ]
158         [ [ type>> { SOS } = ] filter singleton-first decode-scan ]
159     } cleave ;
160
161 : parse-marker ( -- marker )
162     read1 0xFF assert=
163     read1 >marker ;
164
165 : parse-headers ( -- chunks )
166     [ parse-marker dup { SOS } = not ]
167     [
168         2 read be>
169         dup 2 - read <jpeg-chunk>
170     ] [ produce ] keep dip swap suffix ;
171
172 MEMO: zig-zag ( -- zz )
173     {
174         {  0  1  5  6 14 15 27 28 }
175         {  2  4  7 13 16 26 29 42 }
176         {  3  8 12 17 25 30 41 43 }
177         {  9 11 18 24 31 40 44 53 }
178         { 10 19 23 32 39 45 52 54 }
179         { 20 22 33 38 46 51 55 60 }
180         { 21 34 37 47 50 56 59 61 }
181         { 35 36 48 49 57 58 62 63 }
182     } flatten ;
183
184 MEMO: yuv>bgr-matrix ( -- m )
185     {
186         { 1  2.03211  0       }
187         { 1 -0.39465 -0.58060 }
188         { 1  0        1.13983 }
189     } ;
190
191 : wave ( x u -- n ) swap 2 * 1 + * pi * 16 / cos ;
192
193 :: dct-vect ( u v -- basis )
194     { 8 8 } coord-matrix [ { u v } [ wave ] 2map product ] map^2
195     1 u v [ 0 = [ 2 sqrt / ] when ] bi@ 4 / m*n ;
196
197 MEMO: dct-matrix ( -- m ) 64 <iota> [ 8 /mod dct-vect flatten ] map ;
198
199 : mb-dim ( component -- dim )  [ h>> ] [ v>> ] bi 2array ;
200
201 ! : blocks ( component -- seq )
202 !    mb-dim ! coord-matrix flip concat [ [ { 2 2 } v* ] [ v+ ] bi* ] with map ;
203
204 : all-macroblocks ( quot: ( mb -- ) -- )
205     [
206         jpeg>
207         [ dim>> 8 v/n ]
208         [ color-info>> sift { 0 0 } [ mb-dim vmax ] reduce v/ ] bi
209         [ ceiling ] map
210         coord-matrix flip concat
211     ]
212     [ each ] bi* ; inline
213
214 : reverse-zigzag ( b -- b' ) zig-zag swap [ nth ] curry map ;
215
216 : idct-factor ( b -- b' ) dct-matrix vdotm ;
217
218 MEMO: dct-matrix-blas ( -- m ) dct-matrix >float-blas-matrix ;
219 : V.M ( x A -- x.A ) Mtranspose swap M.V ;
220 : idct-blas ( b -- b' ) >float-blas-vector dct-matrix-blas V.M ;
221
222 : idct ( b -- b' ) idct-factor ;
223
224 :: draw-block ( block x,y color-id jpeg-image -- )
225     block dup length>> sqrt >fixnum group flip
226     dup matrix-dim coord-matrix flip
227     [
228         [ '[ _ [ second ] [ first ] bi ] dip nth nth ]
229         [ x,y v+ color-id jpeg-image draw-color ] bi
230     ] with each^2 ;
231
232 : sign-extend ( bits v -- v' )
233     swap [ ] [ 1 - 2^ < ] 2bi
234     [ -1 swap shift 1 + + ] [ drop ] if ;
235
236 : read1-jpeg-dc ( decoder -- dc )
237     [ read1-huff dup ] [ bs>> bs:read ] bi sign-extend ;
238
239 : read1-jpeg-ac ( decoder -- run/ac )
240     [ read1-huff 16 /mod dup ] [ bs>> bs:read ] bi sign-extend 2array ;
241
242 :: decode-block ( color -- pixels )
243     color dc-huff-table>> read1-jpeg-dc color apply-diff
244     64 0 <array> :> coefs
245     0 coefs set-nth
246     0 :> k!
247     [
248         color ac-huff-table>> read1-jpeg-ac
249         [ first 1 + k + k! ] [ second k coefs set-nth ] [ ] tri
250         { 0 0 } = not
251         k 63 < and
252     ] loop
253     coefs color quant-table>> v*
254     reverse-zigzag idct ;
255     
256 :: draw-macroblock-yuv420 ( mb blocks -- )
257     mb { 16 16 } v* :> pos
258     0 blocks nth pos { 0 0 } v+ 0 jpeg> draw-block
259     1 blocks nth pos { 8 0 } v+ 0 jpeg> draw-block
260     2 blocks nth pos { 0 8 } v+ 0 jpeg> draw-block
261     3 blocks nth pos { 8 8 } v+ 0 jpeg> draw-block
262     4 blocks nth 8 group 2 matrix-zoom concat pos 1 jpeg> draw-block
263     5 blocks nth 8 group 2 matrix-zoom concat pos 2 jpeg> draw-block ;
264     
265 :: draw-macroblock-yuv444 ( mb blocks -- )
266     mb { 8 8 } v* :> pos
267     3 <iota> [ [ blocks nth pos ] [ jpeg> draw-block ] bi ] each ;
268
269 :: draw-macroblock-y ( mb blocks -- )
270     mb { 8 8 } v* :> pos
271     0 blocks nth pos 0 jpeg> draw-block
272     64 0 <array> pos 1 jpeg> draw-block
273     64 0 <array> pos 2 jpeg> draw-block ;
274  
275     ! %fixme: color hack
276  !   color h>> 2 =
277  !   [ 8 group 2 matrix-zoom concat ] unless
278  !   pos { 8 8 } v* color jpeg> draw-block ;
279
280 : decode-macroblock ( -- blocks )
281     jpeg> components>>
282     [
283         [ mb-dim first2 * ]
284         [ [ decode-block ] curry replicate ] bi
285     ] map concat ;
286
287 : cleanup-bitstream ( bytes -- bytes' )
288     binary [
289         [
290             { 0xFF } read-until
291             read1 [ 0x00 = and ] keep swap
292         ]
293         [ drop ] produce
294         swap >marker {  EOI } assert=
295         swap suffix
296         { 0xFF } join
297     ] with-byte-reader ;
298
299 : setup-bitmap ( image -- )
300     dup dim>> 16 v/n [ ceiling ] map 16 v*n >>dim
301     BGR >>component-order
302     ubyte-components >>component-type
303     f >>upside-down?
304     dup dim>> first2 * 3 * 0 <array> >>bitmap
305     drop ;
306
307 ERROR: unsupported-colorspace ;
308 SINGLETONS: YUV420 YUV444 Y MAGIC! ;
309
310 :: detect-colorspace ( jpeg-image -- csp )
311     jpeg-image color-info>> sift :> colors
312     MAGIC!
313     colors length 1 = [ drop Y ] when
314     colors length 3 =
315     [
316         colors [ mb-dim { 1 1 } = ] all?
317         [ drop YUV444 ] when
318
319         colors unclip
320         [ [ mb-dim { 1 1 } = ] all? ]
321         [ mb-dim { 2 2 } =  ] bi* and
322         [ drop YUV420 ] when
323     ] when ;
324
325 ! this eats ~50% cpu time
326 : draw-macroblocks ( mbs -- )
327     jpeg> detect-colorspace
328     {
329         { YUV420 [ [ first2 draw-macroblock-yuv420 ] each ] }
330         { YUV444 [ [ first2 draw-macroblock-yuv444 ] each ] }
331         { Y      [ [ first2 draw-macroblock-y ] each ] }
332         [ unsupported-colorspace ]
333     } case ;
334
335 ! this eats ~25% cpu time
336 : color-transform ( yuv -- rgb )
337     { 128 0 0 } v+ yuv>bgr-matrix swap mdotv
338     [ 0 max 255 min >fixnum ] map ;
339
340 : baseline-decompress ( -- )
341     jpeg> bitstream>> cleanup-bitstream { 255 255 255 255 } append
342     >byte-array bs:<msb0-bit-reader> jpeg> bitstream<<
343     jpeg> 
344     [ bitstream>> ] 
345     [ [ [ <huffman-decoder> ] with map ] change-huff-tables drop ] bi
346     jpeg> components>> [ fetch-tables ] each
347     [ decode-macroblock 2array ] collector 
348     [ all-macroblocks ] dip
349     jpeg> setup-bitmap draw-macroblocks 
350     jpeg> bitmap>> 3 <groups> [ color-transform ] map! drop
351     jpeg> [ >byte-array ] change-bitmap drop ;
352
353 ERROR: not-a-jpeg-image ;
354
355 : loading-jpeg>image ( loading-jpeg -- image )
356     dup jpeg-image [
357         baseline-parse
358         baseline-decompress
359     ] with-variable ;
360
361 : load-jpeg ( stream -- loading-jpeg )
362     [
363         parse-marker { SOI } = [ not-a-jpeg-image ] unless
364         parse-headers
365         read-contents <loading-jpeg>
366     ] with-input-stream ;
367
368 PRIVATE>
369
370 M: jpeg-image stream>image*
371     drop load-jpeg loading-jpeg>image ;