aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/python/Pillow/py3/libImaging/ZipEncode.c
blob: edbce36822c4e9ed28ab8f114595c910be206979 (plain) (blame)
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
/*
 * The Python Imaging Library.
 * $Id$
 *
 * coder for ZIP (deflated) image data
 *
 * History:
 * 96-12-29 fl  created
 * 96-12-30 fl  adaptive filter selection, encoder tuning
 *
 * Copyright (c) Fredrik Lundh 1996.
 * Copyright (c) Secret Labs AB 1997.
 *
 * See the README file for information on usage and redistribution.
 */

#include "Imaging.h"

#ifdef HAVE_LIBZ

#include "ZipCodecs.h"

int
ImagingZipEncode(Imaging im, ImagingCodecState state, UINT8 *buf, int bytes) {
    ZIPSTATE *context = (ZIPSTATE *)state->context;
    int err;
    int compress_level, compress_type;
    UINT8 *ptr;
    int i, bpp, s, sum;
    ImagingSectionCookie cookie;

    if (!state->state) {
        /* Initialization */

        /* Valid modes are ZIP_PNG, ZIP_PNG_PALETTE, and ZIP_TIFF */

        /* overflow check for malloc */
        if (state->bytes > INT_MAX - 1) {
            state->errcode = IMAGING_CODEC_MEMORY;
            return -1;
        }

        /* Expand standard buffer to make room for the filter selector,
           and allocate filter buffers */
        free(state->buffer);
        /* malloc check ok, overflow checked above */
        state->buffer = (UINT8 *)malloc(state->bytes + 1);
        context->previous = (UINT8 *)malloc(state->bytes + 1);
        context->prior = (UINT8 *)malloc(state->bytes + 1);
        context->up = (UINT8 *)malloc(state->bytes + 1);
        context->average = (UINT8 *)malloc(state->bytes + 1);
        context->paeth = (UINT8 *)malloc(state->bytes + 1);
        if (!state->buffer || !context->previous || !context->prior || !context->up ||
            !context->average || !context->paeth) {
            free(context->paeth);
            free(context->average);
            free(context->up);
            free(context->prior);
            free(context->previous);
            state->errcode = IMAGING_CODEC_MEMORY;
            return -1;
        }

        /* Initialise filter buffers */
        state->buffer[0] = 0;
        context->prior[0] = 1;
        context->up[0] = 2;
        context->average[0] = 3;
        context->paeth[0] = 4;

        /* Initialise previous buffer to black */
        memset(context->previous, 0, state->bytes + 1);

        /* Setup compression context */
        context->z_stream.zalloc = (alloc_func)0;
        context->z_stream.zfree = (free_func)0;
        context->z_stream.opaque = (voidpf)0;
        context->z_stream.next_in = 0;
        context->z_stream.avail_in = 0;

        compress_level =
            (context->optimize) ? Z_BEST_COMPRESSION : context->compress_level;

        if (context->compress_type == -1) {
            compress_type =
                (context->mode == ZIP_PNG) ? Z_FILTERED : Z_DEFAULT_STRATEGY;
        } else {
            compress_type = context->compress_type;
        }

        err = deflateInit2(
            &context->z_stream,
            /* compression level */
            compress_level,
            /* compression method */
            Z_DEFLATED,
            /* compression memory resources */
            15,
            9,
            /* compression strategy (image data are filtered)*/
            compress_type);
        if (err < 0) {
            state->errcode = IMAGING_CODEC_CONFIG;
            return -1;
        }

        if (context->dictionary && context->dictionary_size > 0) {
            err = deflateSetDictionary(
                &context->z_stream,
                (unsigned char *)context->dictionary,
                context->dictionary_size);
            if (err < 0) {
                state->errcode = IMAGING_CODEC_CONFIG;
                return -1;
            }
        }

        /* Ready to decode */
        state->state = 1;
    }

    /* Setup the destination buffer */
    context->z_stream.next_out = buf;
    context->z_stream.avail_out = bytes;
    if (context->z_stream.next_in && context->z_stream.avail_in > 0) {
        /* We have some data from previous round, deflate it first */
        err = deflate(&context->z_stream, Z_NO_FLUSH);

        if (err < 0) {
            /* Something went wrong inside the compression library */
            if (err == Z_DATA_ERROR) {
                state->errcode = IMAGING_CODEC_BROKEN;
            } else if (err == Z_MEM_ERROR) {
                state->errcode = IMAGING_CODEC_MEMORY;
            } else {
                state->errcode = IMAGING_CODEC_CONFIG;
            }
            free(context->paeth);
            free(context->average);
            free(context->up);
            free(context->prior);
            free(context->previous);
            deflateEnd(&context->z_stream);
            return -1;
        }
    }

    ImagingSectionEnter(&cookie);
    for (;;) {
        switch (state->state) {
            case 1:

                /* Compress image data */
                while (context->z_stream.avail_out > 0) {
                    if (state->y >= state->ysize) {
                        /* End of image; now flush compressor buffers */
                        state->state = 2;
                        break;
                    }

                    /* Stuff image data into the compressor */
                    state->shuffle(
                        state->buffer + 1,
                        (UINT8 *)im->image[state->y + state->yoff] +
                            state->xoff * im->pixelsize,
                        state->xsize);

                    state->y++;

                    context->output = state->buffer;

                    if (context->mode == ZIP_PNG) {
                        /* Filter the image data.  For each line, select
                           the filter that gives the least total distance
                           from zero for the filtered data (taken from
                           LIBPNG) */

                        bpp = (state->bits + 7) / 8;

                        /* 0. No filter */
                        for (i = 1, sum = 0; i <= state->bytes; i++) {
                            UINT8 v = state->buffer[i];
                            sum += (v < 128) ? v : 256 - v;
                        }

                        /* 2. Up.  We'll test this first to save time when
                           an image line is identical to the one above. */
                        if (sum > 0) {
                            for (i = 1, s = 0; i <= state->bytes; i++) {
                                UINT8 v = state->buffer[i] - context->previous[i];
                                context->up[i] = v;
                                s += (v < 128) ? v : 256 - v;
                            }
                            if (s < sum) {
                                context->output = context->up;
                                sum = s; /* 0 if line was duplicated */
                            }
                        }

                        /* 1. Prior */
                        if (sum > 0) {
                            for (i = 1, s = 0; i <= bpp; i++) {
                                UINT8 v = state->buffer[i];
                                context->prior[i] = v;
                                s += (v < 128) ? v : 256 - v;
                            }
                            for (; i <= state->bytes; i++) {
                                UINT8 v = state->buffer[i] - state->buffer[i - bpp];
                                context->prior[i] = v;
                                s += (v < 128) ? v : 256 - v;
                            }
                            if (s < sum) {
                                context->output = context->prior;
                                sum = s; /* 0 if line is solid */
                            }
                        }

                        /* 3. Average (not very common in real-life images,
                           so its only used with the optimize option) */
                        if (context->optimize && sum > 0) {
                            for (i = 1, s = 0; i <= bpp; i++) {
                                UINT8 v = state->buffer[i] - context->previous[i] / 2;
                                context->average[i] = v;
                                s += (v < 128) ? v : 256 - v;
                            }
                            for (; i <= state->bytes; i++) {
                                UINT8 v =
                                    state->buffer[i] -
                                    (state->buffer[i - bpp] + context->previous[i]) / 2;
                                context->average[i] = v;
                                s += (v < 128) ? v : 256 - v;
                            }
                            if (s < sum) {
                                context->output = context->average;
                                sum = s;
                            }
                        }

                        /* 4. Paeth */
                        if (sum > 0) {
                            for (i = 1, s = 0; i <= bpp; i++) {
                                UINT8 v = state->buffer[i] - context->previous[i];
                                context->paeth[i] = v;
                                s += (v < 128) ? v : 256 - v;
                            }
                            for (; i <= state->bytes; i++) {
                                UINT8 v;
                                int a, b, c;
                                int pa, pb, pc;

                                /* fetch pixels */
                                a = state->buffer[i - bpp];
                                b = context->previous[i];
                                c = context->previous[i - bpp];

                                /* distances to surrounding pixels */
                                pa = abs(b - c);
                                pb = abs(a - c);
                                pc = abs(a + b - 2 * c);

                                /* pick predictor with the shortest distance */
                                v = state->buffer[i] - ((pa <= pb && pa <= pc) ? a
                                                        : (pb <= pc)           ? b
                                                                               : c);
                                context->paeth[i] = v;
                                s += (v < 128) ? v : 256 - v;
                            }
                            if (s < sum) {
                                context->output = context->paeth;
                                sum = s;
                            }
                        }
                    }

                    /* Compress this line */
                    context->z_stream.next_in = context->output;
                    context->z_stream.avail_in = state->bytes + 1;

                    err = deflate(&context->z_stream, Z_NO_FLUSH);

                    if (err < 0) {
                        /* Something went wrong inside the compression library */
                        if (err == Z_DATA_ERROR) {
                            state->errcode = IMAGING_CODEC_BROKEN;
                        } else if (err == Z_MEM_ERROR) {
                            state->errcode = IMAGING_CODEC_MEMORY;
                        } else {
                            state->errcode = IMAGING_CODEC_CONFIG;
                        }
                        free(context->paeth);
                        free(context->average);
                        free(context->up);
                        free(context->prior);
                        free(context->previous);
                        deflateEnd(&context->z_stream);
                        ImagingSectionLeave(&cookie);
                        return -1;
                    }

                    /* Swap buffer pointers */
                    ptr = state->buffer;
                    state->buffer = context->previous;
                    context->previous = ptr;
                }

                if (context->z_stream.avail_out == 0) {
                    break; /* Buffer full */
                }

            case 2:

                /* End of image data; flush compressor buffers */

                while (context->z_stream.avail_out > 0) {
                    err = deflate(&context->z_stream, Z_FINISH);

                    if (err == Z_STREAM_END) {
                        free(context->paeth);
                        free(context->average);
                        free(context->up);
                        free(context->prior);
                        free(context->previous);

                        deflateEnd(&context->z_stream);

                        state->errcode = IMAGING_CODEC_END;

                        break;
                    }

                    if (context->z_stream.avail_out == 0) {
                        break; /* Buffer full */
                    }
                }
        }
        ImagingSectionLeave(&cookie);
        return bytes - context->z_stream.avail_out;
    }

    /* Should never ever arrive here... */
    state->errcode = IMAGING_CODEC_CONFIG;
    ImagingSectionLeave(&cookie);
    return -1;
}

/* -------------------------------------------------------------------- */
/* Cleanup                                                              */
/* -------------------------------------------------------------------- */

int
ImagingZipEncodeCleanup(ImagingCodecState state) {
    ZIPSTATE *context = (ZIPSTATE *)state->context;

    if (context->dictionary) {
        free(context->dictionary);
        context->dictionary = NULL;
    }

    return -1;
}

const char *
ImagingZipVersion(void) {
    return zlibVersion();
}

#endif