forked from pixiv/go-libjpeg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
compress.go
442 lines (382 loc) · 11.4 KB
/
compress.go
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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
package jpeg
/*
#include <stdio.h>
#include <stdlib.h>
#include "jpeglib.h"
#include "jpeg.h"
static struct jpeg_compress_struct *new_compress(void) {
struct jpeg_compress_struct *cinfo = (struct jpeg_compress_struct *) calloc(sizeof(struct jpeg_compress_struct), 1);
if (!cinfo) {
return NULL;
}
struct my_error_mgr *jerr = (struct my_error_mgr *)calloc(sizeof(struct my_error_mgr), 1);
if (!jerr) {
free(cinfo);
return NULL;
}
cinfo->err = jpeg_std_error(&jerr->pub);
jerr->pub.error_exit = (void *)error_longjmp;
if (setjmp(jerr->jmpbuf) != 0) {
free(jerr);
free(cinfo);
return NULL;
}
jpeg_create_compress(cinfo);
return cinfo;
}
static void destroy_compress(struct jpeg_compress_struct *cinfo) {
free(cinfo->err);
jpeg_destroy_compress(cinfo);
free(cinfo);
}
static JDIMENSION write_scanlines(j_compress_ptr cinfo, JSAMPROW row, JDIMENSION max_lines, int *msg_code) {
// handle error
struct my_error_mgr *err = (struct my_error_mgr *)cinfo->err;
if (setjmp(err->jmpbuf) != 0) {
*msg_code = err->pub.msg_code;
return 0;
}
*msg_code = 0;
return jpeg_write_scanlines(cinfo, &row, max_lines);
}
static JDIMENSION write_mcu_gray(struct jpeg_compress_struct *cinfo, JSAMPROW pix, int stride, int *msg_code) {
// handle error
struct my_error_mgr *err = (struct my_error_mgr *)cinfo->err;
if (setjmp(err->jmpbuf) != 0) {
*msg_code = err->pub.msg_code;
return 0;
}
// Set height to one MCU size
// because jpeg_write_raw_data processes just one MCU row per call.
int height = DCTSIZE * cinfo->comp_info[0].v_samp_factor;
// Allocate JSAMPIMAGE to hold pointers to one iMCU worth of image data
// this is a safe overestimate; we use the return value from
// jpeg_read_raw_data to figure out what is the actual iMCU row count.
JSAMPROW *rows = alloca(sizeof(JSAMPROW *) * height);
// First fill in the pointers into the plane data buffers
int h = 0;
for (h = 0; h < height; h++) {
rows[h] = &pix[stride * h];
}
// Get the data
*msg_code = 0;
return jpeg_write_raw_data(cinfo, &rows, height);
}
static JDIMENSION write_mcu_ycbcr(struct jpeg_compress_struct *cinfo, JSAMPROW y_row, JSAMPROW cb_row, JSAMPROW cr_row, int y_stride, int c_stride, int *msg_code) {
// handle error
struct my_error_mgr *err = (struct my_error_mgr *)cinfo->err;
if (setjmp(err->jmpbuf) != 0) {
*msg_code = err->pub.msg_code;
return 0;
}
// Allocate JSAMPIMAGE to hold pointers to one iMCU worth of image data
// this is a safe overestimate; we use the return value from
// jpeg_read_raw_data to figure out what is the actual iMCU row count.
int y_h = DCTSIZE * cinfo->comp_info[0].v_samp_factor;
int c_h = DCTSIZE * cinfo->comp_info[1].v_samp_factor;
JSAMPROW *y_rows = alloca(sizeof(JSAMPROW) * y_h);
JSAMPROW *cb_rows = alloca(sizeof(JSAMPROW) * c_h);
JSAMPROW *cr_rows = alloca(sizeof(JSAMPROW) * c_h);
JSAMPARRAY image[] = {y_rows, cb_rows, cr_rows};
int h = 0;
// First fill in the pointers into the plane data buffers
for (h = 0; h < y_h; h++) {
y_rows[h] = &y_row[y_stride * h];
}
for (h = 0; h < c_h; h++) {
cb_rows[h] = &cb_row[c_stride * h];
cr_rows[h] = &cr_row[c_stride * h];
}
// Get the data
*msg_code = 0;
return jpeg_write_raw_data(cinfo, image, y_h);
}
static int start_compress(j_compress_ptr cinfo, boolean write_all_tables)
{
// handle error
struct my_error_mgr *err = (struct my_error_mgr *)cinfo->err;
if (setjmp(err->jmpbuf) != 0) {
return err->pub.msg_code;
}
jpeg_start_compress(cinfo, write_all_tables);
return 0;
}
static int finish_compress(j_compress_ptr cinfo)
{
// handle error
struct my_error_mgr *err = (struct my_error_mgr *)cinfo->err;
if (setjmp(err->jmpbuf) != 0) {
return err->pub.msg_code;
}
jpeg_finish_compress(cinfo);
return 0;
}
*/
import "C"
import (
"errors"
"image"
"io"
"unsafe"
"github.com/pixiv/go-libjpeg/rgb"
)
// EncoderOptions specifies which settings to use during Compression.
type EncoderOptions struct {
Quality int
OptimizeCoding bool
ProgressiveMode bool
DCTMethod DCTMethod
}
func newCompress(w io.Writer) (cinfo *C.struct_jpeg_compress_struct, err error) {
cinfo = C.new_compress()
if cinfo == nil {
err = errors.New("failed to allocate jpeg encoder")
return
}
_, err = makeDestinationManager(w, cinfo)
return
}
func startCompress(cinfo *C.struct_jpeg_compress_struct) error {
code := C.start_compress(cinfo, C.TRUE)
if code != 0 {
return errors.New(jpegErrorMessage(unsafe.Pointer(cinfo)))
}
return nil
}
func destroyCompress(cinfo *C.struct_jpeg_compress_struct) {
if cinfo == nil {
return
}
destinationManager := getDestinationManager(cinfo)
if destinationManager != nil {
releaseDestinationManager(destinationManager)
}
C.destroy_compress(cinfo)
}
func finishCompress(cinfo *C.struct_jpeg_compress_struct) error {
code := C.finish_compress(cinfo)
if code != 0 {
return errors.New(jpegErrorMessage(unsafe.Pointer(cinfo)))
}
return nil
}
func writeScanline(cinfo *C.struct_jpeg_compress_struct, row C.JSAMPROW, maxLines C.JDIMENSION) (line int, err error) {
code := C.int(0)
line = int(C.write_scanlines(cinfo, row, maxLines, &code))
if code != 0 {
err = errors.New(jpegErrorMessage(unsafe.Pointer(cinfo)))
}
return
}
func writeMCUGray(cinfo *C.struct_jpeg_compress_struct, row C.JSAMPROW, stride int) (line int, err error) {
code := C.int(0)
line = int(C.write_mcu_gray(cinfo, row, C.int(stride), &code))
if code != 0 {
err = errors.New(jpegErrorMessage(unsafe.Pointer(cinfo)))
}
return
}
func writeMCUYCbCr(cinfo *C.struct_jpeg_compress_struct, y, cb, cr C.JSAMPROW, yStride, cStride int) (line int, err error) {
code := C.int(0)
line = int(C.write_mcu_ycbcr(cinfo, y, cb, cr, C.int(yStride), C.int(cStride), &code))
if code != 0 {
err = errors.New(jpegErrorMessage(unsafe.Pointer(cinfo)))
}
return
}
// Encode encodes src image and writes into w as JPEG format data.
func Encode(w io.Writer, src image.Image, opt *EncoderOptions) (err error) {
var cinfo *C.struct_jpeg_compress_struct
cinfo, err = newCompress(w)
if err != nil {
return
}
defer destroyCompress(cinfo)
switch s := src.(type) {
case *image.YCbCr:
err = encodeYCbCr(cinfo, s, opt)
case *image.Gray:
err = encodeGray(cinfo, s, opt)
case *image.RGBA:
err = encodeRGBA(cinfo, s, opt)
case *rgb.Image:
err = encodeRGB(cinfo, s, opt)
default:
return errors.New("unsupported image type")
}
return
}
// encode image.YCbCr
func encodeYCbCr(cinfo *C.struct_jpeg_compress_struct, src *image.YCbCr, p *EncoderOptions) (err error) {
// Set up compression parameters
w, h := src.Bounds().Dx(), src.Bounds().Dy()
cinfo.image_width = C.JDIMENSION(w)
cinfo.image_height = C.JDIMENSION(h)
cinfo.input_components = 3
cinfo.in_color_space = C.JCS_YCbCr
setupEncoderOptions(cinfo, p)
compInfo := (*[3]C.jpeg_component_info)(unsafe.Pointer(cinfo.comp_info))
cVDiv := 1
switch src.SubsampleRatio {
case image.YCbCrSubsampleRatio444:
// 1x1,1x1,1x1
compInfo[Y].h_samp_factor, compInfo[Y].v_samp_factor = 1, 1
compInfo[Cb].h_samp_factor, compInfo[Cb].v_samp_factor = 1, 1
compInfo[Cr].h_samp_factor, compInfo[Cr].v_samp_factor = 1, 1
case image.YCbCrSubsampleRatio440:
// 1x2,1x1,1x1
compInfo[Y].h_samp_factor, compInfo[Y].v_samp_factor = 1, 2
compInfo[Cb].h_samp_factor, compInfo[Cb].v_samp_factor = 1, 1
compInfo[Cr].h_samp_factor, compInfo[Cr].v_samp_factor = 1, 1
cVDiv = 2
case image.YCbCrSubsampleRatio422:
// 2x1,1x1,1x1
compInfo[Y].h_samp_factor, compInfo[Y].v_samp_factor = 2, 1
compInfo[Cb].h_samp_factor, compInfo[Cb].v_samp_factor = 1, 1
compInfo[Cr].h_samp_factor, compInfo[Cr].v_samp_factor = 1, 1
case image.YCbCrSubsampleRatio420:
// 2x2,1x1,1x1
compInfo[Y].h_samp_factor, compInfo[Y].v_samp_factor = 2, 2
compInfo[Cb].h_samp_factor, compInfo[Cb].v_samp_factor = 1, 1
compInfo[Cr].h_samp_factor, compInfo[Cr].v_samp_factor = 1, 1
cVDiv = 2
}
// libjpeg raw data in is in planar format, which avoids unnecessary
// planar->packed->planar conversions.
cinfo.raw_data_in = C.TRUE
// Start compression
err = startCompress(cinfo)
if err != nil {
return
}
defer func() {
ferr := finishCompress(cinfo)
if ferr != nil && err == nil {
err = ferr
}
}()
for v := 0; v < h; {
yOff, cOff := v*src.YStride, v/cVDiv*src.CStride
line, err := writeMCUYCbCr(
cinfo,
C.JSAMPROW(unsafe.Pointer(&src.Y[yOff])),
C.JSAMPROW(unsafe.Pointer(&src.Cb[cOff])),
C.JSAMPROW(unsafe.Pointer(&src.Cr[cOff])),
src.YStride,
src.CStride,
)
if err != nil {
return err
}
v += line
}
return
}
// encode image.RGBA
func encodeRGBA(cinfo *C.struct_jpeg_compress_struct, src *image.RGBA, p *EncoderOptions) (err error) {
// Set up compression parameters
w, h := src.Bounds().Dx(), src.Bounds().Dy()
cinfo.image_width = C.JDIMENSION(w)
cinfo.image_height = C.JDIMENSION(h)
cinfo.input_components = 4
cinfo.in_color_space = getJCS_EXT_RGBA()
if cinfo.in_color_space == C.JCS_UNKNOWN {
return errors.New("JCS_EXT_RGBA is not supported (probably built without libjpeg-turbo)")
}
setupEncoderOptions(cinfo, p)
// Start compression
err = startCompress(cinfo)
if err != nil {
return
}
defer func() {
ferr := finishCompress(cinfo)
if ferr != nil && err == nil {
err = ferr
}
}()
for v := 0; v < h; {
line, err := writeScanline(cinfo, C.JSAMPROW(unsafe.Pointer(&src.Pix[v*src.Stride])), C.JDIMENSION(1))
if err != nil {
return err
}
v += line
}
return
}
// encode rgb.Image.
func encodeRGB(cinfo *C.struct_jpeg_compress_struct, src *rgb.Image, p *EncoderOptions) (err error) {
// Set up compression parameters
w, h := src.Bounds().Dx(), src.Bounds().Dy()
cinfo.image_width = C.JDIMENSION(w)
cinfo.image_height = C.JDIMENSION(h)
cinfo.input_components = 3
cinfo.in_color_space = C.JCS_RGB
setupEncoderOptions(cinfo, p)
// Start compression
err = startCompress(cinfo)
if err != nil {
return
}
defer func() {
ferr := finishCompress(cinfo)
if ferr != nil && err == nil {
err = ferr
}
}()
for v := 0; v < h; {
line, err := writeScanline(cinfo, C.JSAMPROW(unsafe.Pointer(&src.Pix[v*src.Stride])), C.JDIMENSION(1))
if err != nil {
return err
}
v += line
}
return
}
// encode image.Gray
func encodeGray(cinfo *C.struct_jpeg_compress_struct, src *image.Gray, p *EncoderOptions) (err error) {
// Set up compression parameters
w, h := src.Bounds().Dx(), src.Bounds().Dy()
cinfo.image_width = C.JDIMENSION(w)
cinfo.image_height = C.JDIMENSION(h)
cinfo.input_components = 1
cinfo.in_color_space = C.JCS_GRAYSCALE
setupEncoderOptions(cinfo, p)
compInfo := (*C.jpeg_component_info)(unsafe.Pointer(cinfo.comp_info))
compInfo.h_samp_factor, compInfo.v_samp_factor = 1, 1
// libjpeg raw data in is in planar format, which avoids unnecessary
// planar->packed->planar conversions.
cinfo.raw_data_in = C.TRUE
// Start compression
err = startCompress(cinfo)
if err != nil {
return
}
defer func() {
ferr := finishCompress(cinfo)
if ferr != nil && err == nil {
err = ferr
}
}()
for v := 0; v < h; {
line, err := writeMCUGray(cinfo, C.JSAMPROW(unsafe.Pointer(&src.Pix[v*src.Stride])), src.Stride)
if err != nil {
return err
}
v += line
}
return
}
func setupEncoderOptions(cinfo *C.struct_jpeg_compress_struct, opt *EncoderOptions) {
C.jpeg_set_defaults(cinfo)
C.jpeg_set_quality(cinfo, C.int(opt.Quality), C.TRUE)
if opt.OptimizeCoding {
cinfo.optimize_coding = C.TRUE
} else {
cinfo.optimize_coding = C.FALSE
}
if opt.ProgressiveMode {
C.jpeg_simple_progression(cinfo)
}
cinfo.dct_method = C.J_DCT_METHOD(opt.DCTMethod)
}