Files
wuffs/std/gif/decode_gif.puffs
T

67 lines
1.7 KiB
Plaintext

// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file.
// The GIF spec is https://www.w3.org/Graphics/GIF/spec-gif89a.txt
pub error "bad GIF header"
pub struct decoder?(
width u32[..65535],
height u32[..65535],
background_color_index u8,
// gct is the Global Color Table: 256 (R, G, B) entries.
//
// TODO: 4 byte per pixel RGBA or BGRA instead of 3 bpp RGB?
gct[3 * 256] u8,
lzw lzw_decoder,
)
pub func decoder.decode?(dst writer1, src reader1)() {
this.decode_header?(src:in.src)
this.decode_lsd?(src:in.src)
}
// decode_header reads either "GIF87a" or "GIF89a".
//
// See the spec section 17 "Header" on page 7.
pri func decoder.decode_header?(src reader1)() {
var c[6] u8
var i u32
while i < 6 {
c[i] = in.src.read_u8?()
i += 1
}
if (c[0] != 0x47) or (c[1] != 0x49) or (c[2] != 0x46) or (c[3] != 0x38) or
((c[4] != 0x37) and (c[4] != 0x39)) or (c[5] != 0x61) {
return error "bad GIF header"
}
}
// decode_lsd reads the Logical Screen Descriptor.
//
// See the spec section 18 "Logical Screen Descriptor" on page 8.
pri func decoder.decode_lsd?(src reader1)() {
var c[7] u8
var i u32
while i < 7 {
c[i] = in.src.read_u8?()
i += 1
}
this.width = (c[0] as u32) | ((c[1] as u32) << 8)
this.height = (c[2] as u32) | ((c[3] as u32) << 8)
this.background_color_index = c[5]
// Read the optional Global Color Table.
if (c[4] & 0x80) != 0 {
var gct_size u32[..256] = (1 as u32) << (1 + (c[4] & 0x07))
i = 0
while i < gct_size {
assert i < 256 via "a < b: a < c; c <= b"(c:gct_size)
this.gct[(3 * i) + 0] = in.src.read_u8?()
this.gct[(3 * i) + 1] = in.src.read_u8?()
this.gct[(3 * i) + 2] = in.src.read_u8?()
i += 1
}
}
}