Debian Codegraph @

decode.go

raw symbols SCIP
1 /*
2 Package golibjpegturbo is the fastest way to decode and encode JPEG images in Go.
3
4 We achieve this via cgo bindings to http://libjpeg-turbo.virtualgl.org library.
5
6 The exact speed depends on the image and CPU. On Mac Book Pro, compared
7 to image/jpeg standard library, golibjpegturbo is:
8
9 * 6x faster when decoding
10
11 * 1.7x faster when encoding at quality level of 90%
12
13 Before you import library, you need to install libjpeg-turbo.
14
15 On Ubuntu: sudo apt-get install libjpeg-turbo8-dev.
16
17 On Mac OS X: brew install libjpeg-turbo
18 */
19 package golibjpegturbo
20
21 // Note: on mac (darwin) /usr/local/opt symlinks to the latest installed version
22 // e.g. /usr/local/Cellar/jpeg-turbo/1.3.1
23
24 /*
25 #cgo linux LDFLAGS: -ljpeg
26 #cgo darwin LDFLAGS: -L/usr/local/opt/jpeg-turbo/lib -ljpeg
27 #cgo darwin CFLAGS: -I/usr/local/opt/jpeg-turbo/include
28
29 #include <stddef.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <jpeglib.h>
33
34 void error_panic(j_common_ptr cinfo);
35 */
36 import "C"
37
38 import (
39 "fmt"
40 "image"
41 "io"
42 "io/ioutil"
43 "reflect"
44 "unsafe"
45 )
46
47 // JpegInfo contains information about JPEG image.
48 type JpegInfo struct {
49 Components int
50 ColorSpace int
51 Width int
52 Height int
53 ColorSpaceString string
54 }
55
56 /*
57 valid combinations of number of components vs. color space:
58
59 JCS_GRAYSCALE => 1
60 JCS_RGB, case JCS_YCbCr => 3
61 JCS_CMYK, JCS_YCCK => 4
62 */
63
64 func colorSpaceToString(cs int) string {
65 if cs == int(C.JCS_GRAYSCALE) {
66 return "grayscale"
67 }
68 if cs == int(C.JCS_YCbCr) {
69 return "ycbcr"
70 }
71 if cs == int(C.JCS_RGB) {
72 return "rgb"
73 }
74 if cs == int(C.JCS_CMYK) {
75 return "cmyk"
76 }
77 if cs == int(C.JCS_YCCK) {
78 return "ycck"
79 }
80 // those seem only to be available for out_color_space i.e. decoded space
81 if cs == int(C.JCS_EXT_RGB) {
82 return "extrgb"
83 }
84 if cs == int(C.JCS_EXT_RGBX) {
85 return "extrgbx"
86 }
87 if cs == int(C.JCS_EXT_BGR) {
88 return "extbgr"
89 }
90 if cs == int(C.JCS_EXT_BGRX) {
91 return "extbgrx"
92 }
93 if cs == int(C.JCS_EXT_XBGR) {
94 return "extxbgr"
95 }
96 if cs == int(C.JCS_EXT_XRGB) {
97 return "extxrgb"
98 }
99 if cs == int(C.JCS_EXT_RGBA) {
100 return "extrgba"
101 }
102 if cs == int(C.JCS_EXT_BGRA) {
103 return "extbgra"
104 }
105 if cs == int(C.JCS_EXT_ABGR) {
106 return "extabgr"
107 }
108 if cs == int(C.JCS_EXT_ARGB) {
109 return "extargb"
110 }
111 return "unknown"
112 }
113
114 // GetJpegInfo returns information about a JPEG image.
115 func GetJpegInfo(d []byte) (info *JpegInfo, err error) {
116 defer func() {
117 if r := recover(); r != nil {
118 info = nil
119 var ok bool
120 err, ok = r.(error)
121 if !ok {
122 err = fmt.Errorf("JPEG error: %v", r)
123 }
124 }
125 }()
126 // those are allocated, not on stack because of
127 // https://groups.google.com/forum/#!topic/golang-nuts/g4yBziN-MZQ
128 cinfo := (*C.struct_jpeg_decompress_struct)(C.malloc(C.size_t(unsafe.Sizeof(C.struct_jpeg_decompress_struct{}))))
129 defer C.free(unsafe.Pointer(cinfo))
130 cinfo.err = (*C.struct_jpeg_error_mgr)(C.malloc(C.size_t(unsafe.Sizeof(C.struct_jpeg_error_mgr{}))))
131 defer C.free(unsafe.Pointer(cinfo.err))
132
133 C.jpeg_std_error(cinfo.err)
134 cinfo.err.error_exit = (*[0]byte)(C.error_panic)
135
136 C.jpeg_CreateDecompress(cinfo, C.JPEG_LIB_VERSION, C.size_t(unsafe.Sizeof(C.struct_jpeg_decompress_struct{})))
137 defer C.jpeg_destroy_decompress(cinfo)
138
139 // TODO: should make a copy in C memory for GC safety?
140 C.jpeg_mem_src(cinfo, (*C.uchar)(unsafe.Pointer(&d[0])), C.ulong(len(d)))
141
142 res := C.jpeg_read_header(cinfo, C.TRUE)
143 if res != C.JPEG_HEADER_OK {
144 err = fmt.Errorf("C.jpeg_reader_header() failed with %d", int(res))
145 return
146 }
147 info = &JpegInfo{}
148 info.Components = int(cinfo.num_components)
149 info.ColorSpace = int(cinfo.jpeg_color_space)
150 info.Width = int(cinfo.output_width)
151 info.Height = int(cinfo.output_height)
152 info.ColorSpaceString = colorSpaceToString(info.ColorSpace)
153 return
154 }
155
156 func decodeToGray(cinfo *C.struct_jpeg_decompress_struct) image.Image {
157 dx := int(cinfo.output_width)
158 nBytes := dx // per one line, 1 byte per pixel
159 dy := int(cinfo.output_height)
160 img := image.NewGray(image.Rect(0, 0, dx, dy))
161
162 // Note: for even greater speed we could decode directly into img.Pix
163 // but that might stop working when moving GC happens
164 bufBytes := C.malloc(C.size_t(nBytes))
165 scanlines := C.JSAMPARRAY(unsafe.Pointer(&bufBytes))
166 buf := sliceFromCBytes(bufBytes, nBytes)
167
168 for y := 0; y < dy; y++ {
169 C.jpeg_read_scanlines(cinfo, scanlines, 1)
170 off := y * img.Stride
171 copy(img.Pix[off:off+nBytes], buf)
172 }
173 C.free(bufBytes)
174 return img
175 }
176
177 // based on https://code.google.com/p/go-wiki/wiki/cgo
178 // The important thing is that it creates []byte slice without copying
179 // memory, for speed
180 func sliceFromCBytes(p unsafe.Pointer, size int) []byte {
181 hdr := reflect.SliceHeader{
182 Data: uintptr(p),
183 Len: size,
184 Cap: size,
185 }
186 slice := *(*[]byte)(unsafe.Pointer(&hdr))
187 return slice
188 }
189
190 // Note: for YCbCr could try to stay within YCbCr space, which might make the
191 // decode->resize->encode loop faster if we avoid conversion to RGBA at any point
192 // However, decoding to YCbCr is more complicated, because it has multiple
193 // variants (4:2:2 etc.)
194 func decodeToRgba(cinfo *C.struct_jpeg_decompress_struct) image.Image {
195 dx := int(cinfo.output_width)
196 nBytes := dx * 4 // per one line, 4 bytes of destination rgba per pixel
197 dy := int(cinfo.output_height)
198 img := image.NewRGBA(image.Rect(0, 0, dx, dy))
199
200 // Note: for even greater speed we could decode directly into img.Pix
201 // but that might stop working when moving GC happens
202 bufBytes := C.malloc(C.size_t(nBytes))
203 scanlines := C.JSAMPARRAY(unsafe.Pointer(&bufBytes))
204 buf := sliceFromCBytes(bufBytes, nBytes)
205
206 for y := 0; y < dy; y++ {
207 C.jpeg_read_scanlines(cinfo, scanlines, 1)
208 off := y * img.Stride
209 copy(img.Pix[off:off+nBytes], buf)
210 }
211
212 C.free(bufBytes)
213 return img
214 }
215
216 // Source is 'Inverted CMYK'
217 // See https://github.com/google/skia/blob/master/src/images/SkImageDecoder_libjpeg.cpp#L340
218 // for explanation
219 func decodeCmykToRgba(cinfo *C.struct_jpeg_decompress_struct) image.Image {
220 dx := int(cinfo.output_width)
221 nBytes := dx * 4 // per one line, 4 bytes of destination rgba per pixel
222 dy := int(cinfo.output_height)
223 img := image.NewRGBA(image.Rect(0, 0, dx, dy))
224
225 bufBytes := C.malloc(C.size_t(nBytes))
226 scanlines := C.JSAMPARRAY(unsafe.Pointer(&bufBytes))
227 buf := sliceFromCBytes(bufBytes, nBytes)
228
229 for y := 0; y < dy; y++ {
230 C.jpeg_read_scanlines(cinfo, scanlines, 1)
231 off := y * img.Stride
232 srcOff := 0
233 for x := 0; x < dx; x++ {
234 c := uint32(buf[srcOff])
235 srcOff++
236 m := uint32(buf[srcOff])
237 srcOff++
238 y := uint32(buf[srcOff])
239 srcOff++
240 k := uint32(buf[srcOff])
241 srcOff++
242
243 r := uint8(c * k / 255)
244 g := uint8(m * k / 255)
245 b := uint8(y * k / 255)
246
247 img.Pix[off] = r
248 off++
249 img.Pix[off] = g
250 off++
251 img.Pix[off] = b
252 off++
253 img.Pix[off] = 255
254 off++
255 }
256 }
257 C.free(bufBytes)
258 return img
259 }
260
261 // DecodeData reads JPEG image from d and returns it as an image.Image.
262 func DecodeData(d []byte) (img image.Image, err error) {
263 defer func() {
264 if r := recover(); r != nil {
265 img = nil
266 var ok bool
267 err, ok = r.(error)
268 if !ok {
269 err = fmt.Errorf("JPEG error: %v", r)
270 }
271 }
272 }()
273
274 // those are allocated from heap, not on stack because of
275 // https://groups.google.com/forum/#!topic/golang-nuts/g4yBziN-MZQ
276 cinfo := (*C.struct_jpeg_decompress_struct)(C.malloc(C.size_t(unsafe.Sizeof(C.struct_jpeg_decompress_struct{}))))
277 defer C.free(unsafe.Pointer(cinfo))
278 cinfo.err = (*C.struct_jpeg_error_mgr)(C.malloc(C.size_t(unsafe.Sizeof(C.struct_jpeg_error_mgr{}))))
279 defer C.free(unsafe.Pointer(cinfo.err))
280
281 C.jpeg_std_error(cinfo.err)
282 cinfo.err.error_exit = (*[0]byte)(C.error_panic)
283
284 C.jpeg_CreateDecompress(cinfo, C.JPEG_LIB_VERSION, C.size_t(unsafe.Sizeof(C.struct_jpeg_decompress_struct{})))
285 defer C.jpeg_destroy_decompress(cinfo)
286
287 // TODO: should make a copy in C memory for GC safety?
288 C.jpeg_mem_src(cinfo, (*C.uchar)(unsafe.Pointer(&d[0])), C.ulong(len(d)))
289
290 res := C.jpeg_read_header(cinfo, C.TRUE)
291 if res != C.JPEG_HEADER_OK {
292 img = nil
293 err = fmt.Errorf("C.jpeg_reader_header() failed with %d", int(res))
294 return
295 }
296 nComp := int(cinfo.num_components)
297
298 // if we're decoding YCbCr image, ask libjpeg to decode directly to RGBA
299 // for speed (as opposed to converting to RGB and doing RGB -> RGBA in Go)
300 // Note: I don't know if JCS_EXT_RGBA is pre-multiplied alpha (like Go)
301 // but it shouldn't matter for decoding (jpeg doesn't have alpha
302 // information, so alpha component should always end up 0xff)
303 if nComp == 3 {
304 cinfo.out_color_space = C.JCS_EXT_RGBA
305 }
306
307 C.jpeg_start_decompress(cinfo)
308 defer C.jpeg_finish_decompress(cinfo)
309
310 if nComp == 1 {
311 img = decodeToGray(cinfo)
312 } else if nComp == 3 {
313 img = decodeToRgba(cinfo)
314 } else if nComp == 4 {
315 img = decodeCmykToRgba(cinfo)
316 } else {
317 err = fmt.Errorf("Invalid number of components (%d)", cinfo.num_components)
318 }
319 return
320 }
321
322 // Decode reads a JPEG image from r and returns it as an image.Image.
323 func Decode(r io.Reader) (image.Image, error) {
324 // loading the whole image is not ideal but doing callbacks is more complicated
325 // so for now do the simple thing
326 d, err := ioutil.ReadAll(r)
327 if err != nil {
328 return nil, err
329 }
330 return DecodeData(d)
331 }