Files
image/image/jpeg/jpeg.sakura
T
2026-11-14 15:42:36 -06:00

81 lines
3.1 KiB
Plaintext

#! Contains JPEG's markers read, which the rest of JPEG's module makes an image
#! of.
#!
#! What JPEG's Huffman coding writes is read: baseline and extended sequential,
#! and progressive, of 8-bit samples, with any sampling factors and restart
#! intervals. Gray, YCbCr, and RGB are read, and CMYK and YCCK as Adobe writes
#! them, without a color profile. Arithmetic coding, lossless JPEG, and 12-bit
#! samples are `unsupported`. Samples are made as libjpeg makes them by default:
#! its accurate integer IDCT, its "fancy" upsampling of chroma halved across,
#! down, or both, and its YCbCr constants. EXIF's orientation is not applied.
#!
#! An image is written as baseline JPEG, as `encode.sakura` says.
module malunal::image::jpeg;
# The natural index of each coefficient, by its place in zigzag order.
const zigzag: u64[64] = [
0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5,
12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28,
35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51,
58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63,
];
#! Reads a JPEG.
#! @param bytes The file's bytes.
#! @returns The image, or `unrecognized` where the bytes don't begin a JPEG,
#! `malformed` where its markers or data are broken, `unsupported` where
#! it's coded in a way not read, and `too_large` where it has too many
#! pixels. Data cut short gives the image as far as it goes.
pub def decode(bytes: span<u8>): result<image, image_error> {
if bytes.length < 4 || bytes[0] != 0xFF || bytes[1] != 0xD8 {
return image_error::unrecognized;
}
var state := decoder { data = bytes, at = 2, components = vector::<component>::new() };
while true {
val marker := state.next_marker() else { break; };
match marker {
0xC0, 0xC1, 0xC2 => {
if state.framed {
return image_error::malformed;
}
state.read_frame(marker == 0xC2) else (e) { return e; };
}
0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF => return image_error::unsupported;
0xC4 => state.read_huffman() else (e) { return e; };
0xDB => state.read_quantization() else (e) { return e; };
0xDD => {
val body := state.segment() else { return image_error::malformed; };
if body.length < 2 {
return image_error::malformed;
}
state.restart = (body[0] as u32 << 8) | body[1] as u32;
}
0xDA => {
if !state.framed {
return image_error::malformed;
}
state.read_scan() else (e) { return e; };
}
0xD9 => break;
0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7 => {}
0xEE => {
val body := state.segment() else { return image_error::malformed; };
if body.length >= 12 && body[0:5] == "Adobe" {
state.adobe = true;
state.transform = body[11];
}
}
else => {
_ = state.segment() else { return image_error::malformed; };
}
}
}
if !state.framed {
return image_error::malformed;
}
return state.finish();
}