gif

read/write GIFs
git clone git://bvnf.space/gm.git
Log | Files | Refs | README

gif.c (7562B)


      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
/* Copyright 2021 (c) phoebos
 *
 * This program reads a gif from stdin or a supplied filename
 * and prints the {global,local} color table then the bitmap
 * where each pixel is a number corresponding to the index of the color.
 */

#include <fcntl.h>
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#define BUF_SIZE 100
#define FAIL_GIF 1
#define FAIL_SYS 2

typedef unsigned char rgb[3];
struct Color_table {
    int len; /* 2- 256 */
    rgb table[256];
};
struct Gif {
    char version[3]; /* 87a or 89a */
    uint16_t width;
    uint16_t height;
    unsigned char flags;        /* ABBBCDDD
                                   A: global colour table [GCT] flag
                                   B+1: colour resolution (bits per primary colour)
                                   C: GCT sort flag (89a+ only)
                                   D+1: bits used per pixel in GCT
                                */
    unsigned char background;   /* color index in GCT of screen background */
    unsigned char aspect_ratio; /* 89a+ only */
    struct Color_table *gct;
    unsigned char *pixels; /* array of indices to colors */
};
struct Image {
    struct Color_table *lct;
    uint16_t left, top, width, height;
    unsigned char flags; /* AB000CCC
                            A: 0 -> use GCT, ignore C
                               1 -> LCT follows, use C
                            B: 0 -> image is in Sequential order
                               1 -> image is in Interlaced order
                            C+1: bits per pixel for this image
                         */
    unsigned char *pixels;
};

void
scan_colortable(struct Color_table *ct, unsigned char *buf) {
    /* TODO: gif87a.txt L 336? */
    int i;
    for (i = 0; i < ct->len; i += 1) {
        rgb c = {*buf++, *buf++, *buf++};
        memcpy(ct->table[i], c, sizeof(rgb));
    }
}

void
print_colortable(struct Color_table *c) {
    for (int i = 0; i < c->len; i++) {
        printf("%d: \033[48;2;%d;%d;%dm(%02x;%02x;%02x)\033[0m\n", i,
               c->table[i][0], c->table[i][1], c->table[i][2], c->table[i][0],
               c->table[i][1], c->table[i][2]);
    }
}

/* gif_decode_image should be called with buf pointing to the separator
 * character, ','. gct should be a pointer to the global color table.
 */
int
gif_decode_image(struct Image *img, struct Color_table *gct,
                     unsigned char *buf) {
    if (*buf++ != ',') {
        fprintf(stderr, "not an image block\n");
        return FAIL_GIF;
    }
    struct Color_table *ct = gct;

    /* Get the top, left, width, and height from the beginning of buf.
     * They are all 2 byte numbers with the LSB first. */
    uint16_t *tmp;
    tmp = (uint16_t *)buf;
    img->left = *tmp;
    buf += 2;
    tmp = (uint16_t *)buf;
    img->top = *tmp;
    buf += 2;
    tmp = (uint16_t *)buf;
    img->width = *tmp;
    buf += 2;
    tmp = (uint16_t *)buf;
    img->height = *tmp;
    buf += 2;

    fprintf(stderr, "image block starts at %d,%d with dimensions %d,%d\n",
            img->left, img->top, img->width, img->height);

    img->flags = *buf++;

    if (img->flags && 0x80) {
        /* local color table follows */
        fprintf(stderr, "using LCT(%d)\n", img->flags && 7);
        scan_colortable(img->lct, buf);
        buf += 3 * img->lct->len;
        print_colortable(img->lct);

        ct = img->lct;
    } else {
        /* use GCT */
        fprintf(stderr, "using GCT, ");
    }

    if (img->flags && 0x40) {
        /* image is interlaced */
        fprintf(stderr, "interlaced\n");
        /* TODO */
        return -1;
    } else {
        /* image is sequential */
        fprintf(stderr, "sequential\n");
    }

    return 0;
}

int
gif_decode(unsigned char *buf, size_t len) {
    struct Gif g = {0};
    g.gct = malloc(sizeof(struct Color_table));
    if (g.gct == NULL) {
        perror("malloc");
        exit(FAIL_SYS);
    }
    struct Image *img;
    int cur_block;
    enum { HEAD = 1, SPEC = 2, IMGE = 4 };
    cur_block = HEAD;
    (void)cur_block;

    if (strncmp((char *)buf, "GIF", 3))
        return FAIL_GIF;
    buf += 3;
    len -= 3;
    strncpy(g.version, (char *)buf, 3);
    fprintf(stderr, "GIF version %s, ", g.version);
    buf += 3;
    len -= 3;

    uint16_t *tmp;

    tmp = (uint16_t *)buf;
    g.width = *tmp;
    buf += 2;

    tmp = (uint16_t *)buf;
    g.height = *tmp;
    buf += 2;

    fprintf(stderr, "%d x %d\n", g.width, g.height);

    g.flags = *buf++;
    g.background = *buf++;
    g.aspect_ratio = *buf++;

    g.gct->len = (int)pow(2.0, (double)(g.flags & 7U) + 1);
    fprintf(stderr, "%d colors in GCT\n", g.gct->len);

    /* if GCT... */
    if (g.flags & 0x80) {
        scan_colortable(g.gct, buf);
        buf += 3 * g.gct->len;
    }

    print_colortable(g.gct);

    /* END OF HEADER */

    while (--len) {
        ++buf;
        switch (*buf) {
        case '!':
            if (cur_block != SPEC) {
                cur_block = SPEC;
            }
            break;
        case ',':
            if (cur_block != IMGE) {
                cur_block = IMGE;
                img = malloc(sizeof(struct Image));
                if (img == NULL) {
                    perror("malloc");
                    exit(FAIL_SYS);
                }
                img->lct = malloc(sizeof(struct Color_table));
                if (img->lct == NULL) {
                    perror("malloc");
                    exit(FAIL_SYS);
                }
                img->lct->len = g.gct->len;
                int ret;
                ret = gif_decode_image(img, g.gct, buf);
                if (ret != 0)
                    return ret;
            }
            break;
        case ';':
            /* last char of image section */
            return 0;
        }
    }
    free(img);

    return 0;
}

int
main(int argc, char **argv) {
    int fd;

    /* only work on one file */
    if (argc > 2) {
        fprintf(stderr, "too many args\n");
        return FAIL_SYS;
    }

    ++argv;
    /* stdin */
    if (argc == 1 || **argv == '-')
        fd = 0;
    else {
        /* open named file */
        fd = open(*argv, O_RDONLY);
        if (fd == -1) {
            perror(*argv);
            return FAIL_SYS;
        }
    }

    unsigned char *buf;
    buf = malloc(BUF_SIZE);
    if (buf == NULL) {
        perror("malloc");
        exit(FAIL_SYS);
    }

    /* read the whole file from fd into buf. */
    ssize_t bytes;
    size_t size, used;
    unsigned char *tmp;
    used = 0;
    size = BUF_SIZE; /* initial size from malloc(BUF_SIZE) above */

    while (1) {
        if (used + BUF_SIZE + 1 > size) {
            size = used + BUF_SIZE + 1;
            tmp = realloc(buf, size);
            if (tmp == NULL) {
                /* out of memory */
                perror("realloc");
                free(buf);
                return FAIL_SYS;
            }
            buf = tmp;
        }
        bytes = read(fd, buf + used, BUF_SIZE);
        if (bytes == 0)
            break; /* EOF */
        if (bytes < 0) {
            perror("read");
            return FAIL_SYS;
        }
        used += bytes;
    }

    if (close(fd) != 0) {
        perror("close");
        return FAIL_SYS;
    }

    int ret = gif_decode(buf, used);
    switch (ret) {
    case FAIL_GIF:
        fprintf(stderr, "error: invalid GIF format\n");
        return FAIL_GIF;
    case 0:
        break;
    default:
        return ret;
    }

    free(buf);
    return 0;
}