semmixcolor and perception

General structure of a GIF file

A GIF file is a sequence of blocks laid end to end. Each starts with a byte that says what it is, so a decoder can read the file from start to finish without seeking and without a table of contents.

Layout

header "GIF87a" or "GIF89a" 6 bytes logical screen descriptor dimensions, flags, background 7 bytes [global color table] 3 · 2^(N+1) bytes, optional any number of times, in any order: [extension] 21 xx ... GIF89a image block 2C ... [local color table] LZW data trailer 3B 1 byte

The exact ordering rules are on the block order page.

Identifying bytes

ByteASCIIBlock
2C,image descriptor
21!extension, the next byte is its label
3B;trailer

The values were chosen to be readable characters: comma, exclamation mark and semicolon. In the early days that made files easier to inspect and to send over text links.

Data sub-blocks

Variable-length data (the compressed image, comment text, application data) is split into sub-blocks. Each sub-block starts with a length byte from 1 to 255, followed by that many data bytes. The sequence ends with a sub-block of length 0, the terminator:

05 04 12 30 13 05 00 │ └─ 5 bytes ──┘ └ terminator └ sub-block length

This lets a decoder skip a block it does not understand: it reads the length bytes and jumps over the data until it hits 00. It does not need to know the contents to know where the block ends.

Little-endian numbers

16-bit numbers (dimensions, positions, delays) are stored least significant byte first:

04 00 → 0x0004 = 4 2C 01 → 0x012C = 300 FF FF → 0xFFFF = 65,535 (the largest possible dimension)

Packed fields

Several blocks have a flag byte (packed fields) in which individual bits mean different things. Bits are numbered from the most significant (7) to the least (0). An example from the logical screen descriptor:

F1 = 11110001 │└┬┘│└┬┘ │ │ │ └─ global color table size: 001 → 2^(1+1) = 4 colors │ │ └─── table sorted: 0 (no) │ └───── color resolution: 111 → 8 bits └─────── global color table present: 1 (yes)

Each field is detailed on the page for its block. The complete example file, byte by byte, is in the introduction.