summaryrefslogtreecommitdiffstats
path: root/apps/plugins/imageviewer/gif/gif_decoder.c
blob: f57eab1cf14edcbed98e5e506324eccd0a0ad922 (plain)
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
/***************************************************************************
 *             __________               __   ___.
 *   Open      \______   \ ____   ____ |  | _\_ |__   _______  ___
 *   Source     |       _//  _ \_/ ___\|  |/ /| __ \ /  _ \  \/  /
 *   Jukebox    |    |   (  <_> )  \___|    < | \_\ (  <_> > <  <
 *   Firmware   |____|_  /\____/ \___  >__|_ \|___  /\____/__/\_ \
 *                     \/            \/     \/    \/            \/
 *
 * Copyright (c) 2012 Marcin Bukat
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
 * KIND, either express or implied.
 *
 ****************************************************************************/

#include <lib/pluginlib_bmp.h>
#include "bmp.h"
#if LCD_DEPTH < 8
#include <lib/grey.h>
#endif

#include "gif_lib.h"
#include "gif_decoder.h"

#ifndef resize_bitmap
#if defined(HAVE_LCD_COLOR)
#define resize_bitmap   smooth_resize_bitmap
#else
#define resize_bitmap   grey_resize_bitmap
#endif
#endif

#if defined(HAVE_LCD_COLOR)
typedef struct uint8_rgb pixel_t;
#define NATIVE_SZ (GifFile->SWidth*GifFile->SHeight*FB_DATA_SZ)
#define PIXEL_TRANSPARENT 0x00
#else
typedef unsigned char pixel_t;
#define NATIVE_SZ (GifFile->SWidth*GifFile->SHeight)
#define PIXEL_TRANSPARENT 0xff
#endif

#define PIXELS_SZ (GifFile->SWidth*GifFile->SHeight*sizeof(pixel_t))

static GifFileType *GifFile;

static void gif2pixels(GifPixelType *Line, pixel_t *out,
                       int Row, int Col, int Width)
{
    int x;
#ifndef HAVE_LCD_COLOR
    struct uint8_rgb rgb;
#endif

    GifColorType *ColorMapEntry;

    /* Color map to use */
    ColorMapObject *ColorMap = (GifFile->Image.ColorMap ?
                                GifFile->Image.ColorMap :
                                GifFile->SColorMap);

    pixel_t *pixel = out + ((Row * GifFile->SWidth) + Col);

    for (x = 0; x < Width; x++, pixel++)
    {
        ColorMapEntry = &ColorMap->Colors[Line[x]];

        if (GifFile->Image.GCB &&
            GifFile->Image.GCB->TransparentColor == Line[x])
            continue;

#ifdef HAVE_LCD_COLOR
        pixel->red = ColorMapEntry->Red;
        pixel->green = ColorMapEntry->Green;
        pixel->blue = ColorMapEntry->Blue;
#else
        rgb.red = ColorMapEntry->Red;
        rgb.green = ColorMapEntry->Green;
        rgb.blue = ColorMapEntry->Blue;

        *pixel = brightness(rgb);
#endif
    }
}

static void pixels2native(struct scaler_context *ctx,
                          pixel_t *pixels_buffer,
                          int Row)
{
#ifdef HAVE_LCD_COLOR
    const struct custom_format *cformat = &format_native;
#else
    const struct custom_format *cformat = &format_grey;
#endif

    void (*output_row_8)(uint32_t, void*, struct scaler_context*) =
        cformat->output_row_8;

    output_row_8(Row, (void *)(pixels_buffer + (Row*ctx->bm->width)), ctx);
}

void gif_decoder_init(struct gif_decoder *d, void *mem, size_t size)
{
    memset(d, 0, sizeof(struct gif_decoder));

    d->mem = mem;
    d->mem_size = size;

    /* mem allocator init */
    init_memory_pool(d->mem_size, d->mem);
}

void gif_open(char *filename, struct gif_decoder *d)
{
    if ((GifFile = DGifOpenFileName(filename, &d->error)) == NULL)
        return;

    d->width = GifFile->SWidth;
    d->height = GifFile->SHeight;
    d->frames_count = 0;
}

static void set_canvas_background(pixel_t *out, GifFileType *GifFile)
{
    /* Reading Gif spec it seems one should always use background color
     * in canvas but most real files omit this and sets background color to 0
     * (which IS valid index). We can choose to either conform to standard
     * (and wrongly display most of gifs with transparency) or stick to
     * common practise and treat background color 0 as transparent.
     * Moreover when dispose method is BACKGROUND spec suggest
     * to reset canvas to global background color specified in gif BUT
     * all renderers I know use transparency instead.
     */
    memset(out, PIXEL_TRANSPARENT, PIXELS_SZ);
}

/* var names adhere to giflib coding style */
void gif_decode(struct gif_decoder *d,
                void (*pf_progress)(int current, int total))
{
    int i, j;

    int Size;
    int Row;
    int Col;
    int Width;
    int Height;
    int ExtCode;

    GifPixelType *Line;

    GifRecordType RecordType;
    GifByteType *Extension;

    unsigned char *out = NULL;

    /* The way Interlaced image should
     * be read - offsets and jumps
     */
    const char InterlacedOffset[] = { 0, 4, 2, 1 };
    const char InterlacedJumps[] = { 8, 8, 4, 2 };

    /* used for color conversion */
    struct bitmap bm;
    struct scaler_context ctx = {
        .bm = &bm,
        .dither = 0
    };

    /* initialize struct */
    memset(&bm, 0, sizeof(struct bitmap));

    Size = GifFile->SWidth * sizeof(GifPixelType); /* Size in bytes one row.*/
    Line = (GifPixelType *)malloc(Size);
    if (Line == NULL)
    {
        /* error allocating temp space */
        d->error = D_GIF_ERR_NOT_ENOUGH_MEM;
        return;
    }

    /* We use two pixel buffers if dispose method asks
     * for restoration of the previous state.
     * We only swap the indexes leaving data in place.
     */
    int buf_idx = 0;
    pixel_t *pixels_buffer[2];
    pixels_buffer[0] = (pixel_t *)malloc(PIXELS_SZ);
    pixels_buffer[1] = NULL;

    if (pixels_buffer[0] == NULL)
    {
        d->error = D_GIF_ERR_NOT_ENOUGH_MEM;
        return;
    }

    /* Global background color */
    set_canvas_background(pixels_buffer[0], GifFile);

    bm.width = GifFile->SWidth;
    bm.height = GifFile->SHeight;
    d->native_img_size = NATIVE_SZ;

    if (pf_progress != NULL)
        pf_progress(0, 100);

    /* Scan the content of the GIF file and load the image(s) in: */
    do
    {
        if (DGifGetRecordType(GifFile, &RecordType) == GIF_ERROR)
        {
            d->error = GifFile->Error;
            return;
        }

        switch (RecordType)
        {
            case IMAGE_DESC_RECORD_TYPE:

                if (DGifGetImageDesc(GifFile) == GIF_ERROR)
                {
                    d->error = GifFile->Error;
                    return;
                }

                /* Image Position relative to canvas */
                Row = GifFile->Image.Top;
                Col = GifFile->Image.Left;
                Width = GifFile->Image.Width;
                Height = GifFile->Image.Height;

                /* Check Color map to use */
                if (GifFile->Image.ColorMap == NULL &&
                    GifFile->SColorMap == NULL)
                {
                    d->error = D_GIF_ERR_NO_COLOR_MAP;
                    return;
                }

                /* sanity check */
                if (GifFile->Image.Left+GifFile->Image.Width>GifFile->SWidth ||
                    GifFile->Image.Top+GifFile->Image.Height>GifFile->SHeight)
                {
                    d->error = D_GIF_ERR_DATA_TOO_BIG;
                    return;
                }

                if (GifFile->Image.GCB &&
                    GifFile->Image.GCB->DisposalMode == DISPOSE_PREVIOUS)
                {
                    /* We need to take a snapshot before processing the image
                     * in order to restore canvas to previous state after
                     * rendering
                     */
                     buf_idx ^= 1;

                     if (pixels_buffer[buf_idx] == NULL)
                         pixels_buffer[buf_idx] = (pixel_t *)malloc(PIXELS_SZ);
                }

                if (GifFile->Image.Interlace)
                {
                    /* Need to perform 4 passes on the image */
                    for (i = 0; i < 4; i++)
                    {
                        for (j = Row + InterlacedOffset[i];
                             j < Row + Height;
                             j += InterlacedJumps[i])
                        {
                            if (DGifGetLine(GifFile, Line, Width) == GIF_ERROR)
                            {
                                d->error = GifFile->Error;
                                return;
                            }

                            gif2pixels(Line, pixels_buffer[buf_idx],
                                       Row + j, Col, Width);
                        }

                        if (pf_progress != NULL)
                            pf_progress(25*(i+1), 100);
                    }
                }
                else
                {
                    for (i = 0; i < Height; i++)
                    {
                        /* load single line into buffer */
                        if (DGifGetLine(GifFile,  Line, Width) == GIF_ERROR)
                        {
                            d->error = GifFile->Error;
                            return;
                        }

                        gif2pixels(Line, pixels_buffer[buf_idx],
                                   Row + i, Col, Width);

                        if (pf_progress != NULL)
                            pf_progress(25*(i+1), 100);
                    }
                }

                /* allocate space for new frame */
                out = realloc(out, d->native_img_size*(d->frames_count + 1));
                if (out == NULL)
                {
                    d->error = D_GIF_ERR_NOT_ENOUGH_MEM;
                    return;
                }

                bm.data = out + d->native_img_size*d->frames_count;

                /* animated gif */
                if (GifFile->Image.GCB && GifFile->Image.GCB->DelayTime != 0)
                {
                    for (i=0; i < ctx.bm->height; i++)
                        pixels2native(&ctx, (void *)pixels_buffer[buf_idx], i);

                    /* restore to the background color */
                    switch (GifFile->Image.GCB->DisposalMode)
                    {
                        case DISPOSE_BACKGROUND:
                            set_canvas_background(pixels_buffer[buf_idx],
                                                  GifFile);
                            break;

                        case DISPOSE_PREVIOUS:
                            buf_idx ^= 1;
                            break;

                        default:
                            /* DISPOSAL_UNSPECIFIED
                             * DISPOSE_DO_NOT
                             */
                            break;
                    }

                    d->frames_count++;
                }

                break;

            case EXTENSION_RECORD_TYPE:
                if (DGifGetExtension(GifFile, &ExtCode, &Extension) ==
                    GIF_ERROR)
                {
                    d->error = GifFile->Error;
                    return;
                }

                if (ExtCode == GRAPHICS_EXT_FUNC_CODE)
                {
                    if (GifFile->Image.GCB == NULL)
                        GifFile->Image.GCB = (GraphicsControlBlock *)
                            malloc(sizeof(GraphicsControlBlock));

                    if (DGifExtensionToGCB(Extension[0],
                                           Extension + 1,
                                           GifFile->Image.GCB) == GIF_ERROR)
                    {
                        d->error = GifFile->Error;
                        return;
                    }
                    d->delay = GifFile->Image.GCB->DelayTime;
                }

                /* Skip anything else */
                while (Extension != NULL)
                {
                    if (DGifGetExtensionNext(GifFile, &Extension) == GIF_ERROR)
                    {
                        d->error = GifFile->Error;
                        return;
                    }
                }
                break;

            /* including TERMINATE_RECORD_TYPE */
            default:
                break;
        }

    } while (RecordType != TERMINATE_RECORD_TYPE);

    /* free all internal allocated data */
    if (DGifCloseFile(GifFile) == GIF_ERROR)
    {
        d->error = GifFile->Error;
        return;
    }

    /* not animated gif */
    if (d->frames_count == 0)
    {
        for (i=0; i < ctx.bm->height; i++)
            pixels2native(&ctx, (void *)pixels_buffer[buf_idx], i);

        d->frames_count++;
    }

    free(pixels_buffer[0]);
    if (pixels_buffer[1])
        free(pixels_buffer[1]);

    free(Line);

    /* WARNING !!!! */
    /* GifFile object is trashed from now on, DONT use it */
    /* Move bitmap in native format to the front of the buff */
    memmove(d->mem, out, d->frames_count*d->native_img_size);

    /* correct aspect ratio */
#if (LCD_PIXEL_ASPECT_HEIGHT != 1 || LCD_PIXEL_ASPECT_WIDTH != 1)
    struct bitmap img_src, img_dst;    /* scaler vars */
    struct dim dim_src, dim_dst;       /* recalc_dimensions vars */
    size_t c_native_img_size;          /* size of the image after correction */

    dim_src.width = bm.width;
    dim_src.height = bm.height;

    dim_dst.width = bm.width;
    dim_dst.height = bm.height;

    /* defined in apps/recorder/resize.c */
    if (!recalc_dimension(&dim_dst, &dim_src))
    {
        /* calculate 'corrected' image size */
#ifdef HAVE_LCD_COLOR
        c_native_img_size = dim_dst.width * dim_dst.height * FB_DATA_SZ;
#else
        c_native_img_size = dim_dst.width * dim_dst.height;
#endif

        /* check memory constraints
         * do the correction only if there is enough
         * free memory
         */
        if (d->native_img_size*d->frames_count + c_native_img_size <=
            d->mem_size)
        {
            img_dst.width = dim_dst.width;
            img_dst.height = dim_dst.height;
            img_dst.data = (unsigned char *)d->mem +
                                            d->native_img_size*d->frames_count;

            for (i = 0; i < d->frames_count; i++)
            {
                img_src.width = dim_src.width;
                img_src.height = dim_src.height;
                img_src.data = (unsigned char *)d->mem + i*d->native_img_size;

                /* scale the bitmap to correct physical
                 * pixel dimentions
                 */
                resize_bitmap(&img_src, &img_dst);

                /* copy back corrected image */
                memmove(d->mem + i*c_native_img_size,
                        img_dst.data,
                        c_native_img_size);
            }

            /* update decoder struct */
            d->width = img_dst.width;
            d->height = img_dst.height;
            d->native_img_size = c_native_img_size;
        }
    }
#endif
}