image.codec\codec\gif_encode.mbt
100% · 182 / 182 points · 323 linesBackground color reports the state of each line. Underlined characters mark exact instrumented byte offsets; hover them to inspect the visit count.
- 1
///| - 2
/// # GIF 编码器 GIF Encoder - 3
/// - 4
/// 纯 MoonBit GIF89a 编码器,使用 3-3-2 均匀量化(256 色调色板)+ LZW 压缩。 Pure MoonBit GIF89a encoder using 3-3-2 uniform quantization (256-color palette) + LZW compression. - 5
/// - 6
/// 核心函数 Core functions: - 7
/// - `encode_gif_pure` - 编码单帧 GIF Encode single-frame GIF - 8
/// - `encode_gif_animation_pure` - 编码动画 GIF Encode animated GIF - 9
- 10
// 纯 MoonBit GIF 编码器 - 11
// 单帧 GIF89a,使用 3-3-2 均匀量化(256 色调色板)+ LZW 压缩 - 12
// 移植自 src/format/gif_encode.mbt:1-177,仅替换类型引用: - 13
// @core.Image -> @types.Image, @core.LoadError -> @types.LoadError - 14
- 15
// 3-3-2 量化: R 8 levels, G 8 levels, B 4 levels = 256 colors - 16
- 17
///| - 18
fn quantize_332(r : Int32, g : Int32, b : Int32) -> Int32 { - 19●
let r_level = (r >> 5) & 0x07 - 20
let g_level = (g >> 5) & 0x07 - 21
let b_level = (b >> 6) & 0x03 - 22
r_level * 32 + g_level * 4 + b_level - 23
} - 24
- 25
// 构建 256 色 3-3-2 调色板 - 26
- 27
///| - 28
fn build_332_palette() -> Array[Byte] { - 29●
let palette : Array[Byte] = Array::make(768, b'\x00') - 30
for i in 0..<256 { - 31●
let r_level = i / 32 - 32
let g_level = i % 32 / 4 - 33
let b_level = i % 4 - 34●
palette[i * 3] = (r_level * 36).to_byte() - 35●
palette[i * 3 + 1] = (g_level * 36).to_byte() - 36●
palette[i * 3 + 2] = (b_level * 85).to_byte() - 37
} - 38
palette - 39
} - 40
- 41
// LZW 压缩用于 GIF - 42
// 返回压缩后的字节数组(包含 sub-block 包装) - 43
- 44
///| - 45
fn lzw_compress(indices : Array[Int32], min_code_size : Int32) -> Bytes { - 46●
let clear_code = 1 << min_code_size - 47
let end_code = clear_code + 1 - 48
let code_table : Array[(Int32, Int32)] = [] // (prefix_code, pixel_value) pairs - 49
// 初始化 code table - 50
for i in 0..<clear_code { - 51●
code_table.push((-1, i)) - 52
} - 53●
code_table.push((-1, -1)) // clear code - 54●
code_table.push((-1, -1)) // end code - 55
let next_code = Ref(clear_code + 2) - 56
let code_size = Ref(min_code_size + 1) - 57
let max_code = Ref((1 << code_size.val) - 1) - 58
// 输出位流 - 59
let bit_buffer = Ref(0) - 60
let bit_count = Ref(0) - 61
let output : Array[Byte] = [] - 62
fn emit_code(code : Int32) -> Unit { - 63●
bit_buffer.val = bit_buffer.val | (code << bit_count.val) - 64
bit_count.val += code_size.val - 65
while bit_count.val >= 8 { - 66●
output.push((bit_buffer.val & 0xFF).to_byte()) - 67
bit_buffer.val = bit_buffer.val >> 8 - 68
bit_count.val -= 8 - 69
} - 70
} - 71●
emit_code(clear_code) - 72●
if indices.length() > 0 { - 73●
let prefix = Ref(indices[0]) - 74●
for i in 1..<indices.length() { - 75●
let pixel = indices[i] - 76
// 查找 (prefix, pixel) 在 code table 中 - 77
let found = Ref(-1) - 78●
for j in 0..<code_table.length() { - 79●
let (p, v) = code_table[j] - 80
if p == prefix.val && v == pixel { - 81●
found.val = j - 82
break - 83
} - 84
} - 85
if found.val >= 0 { - 86●
prefix.val = found.val - 87
} else { - 88●
emit_code(prefix.val) - 89
if next_code.val < 4096 { - 90●
code_table.push((prefix.val, pixel)) - 91
if next_code.val > max_code.val && code_size.val < 12 { - 92●
code_size.val += 1 - 93
max_code.val = (1 << code_size.val) - 1 - 94
} - 95
next_code.val += 1 - 96
} - 97
prefix.val = pixel - 98
} - 99
} - 100●
emit_code(prefix.val) - 101
} - 102●
emit_code(end_code) - 103
// 刷新剩余位 - 104
if bit_count.val > 0 { - 105●
output.push((bit_buffer.val & 0xFF).to_byte()) - 106
} - 107
// 包装为 sub-blocks (每块最多 255 字节) - 108
let result : Array[Byte] = [] - 109
let pos = Ref(0) - 110●
while pos.val < output.length() { - 111●
let block_size = if output.length() - pos.val > 255 { - 112●
255 - 113
} else { - 114●
output.length() - pos.val - 115
} - 116●
result.push(block_size.to_byte()) - 117
for i in 0..<block_size { - 118●
result.push(output[pos.val + i]) - 119
} - 120
pos.val += block_size - 121
} - 122●
result.push(b'\x00') // block terminator - 123●
Bytes::from_array(result) - 124
} - 125
- 126
///| - 127
/// 将 Image 编码为单帧 GIF89a 字节流,使用 3-3-2 均匀量化(256 色调色板)+ LZW 压缩,输入 channels 应为 3 (RGB) 或 4 (RGBA,alpha 忽略) Encode Image to single-frame GIF89a byte stream, Uses 3-3-2 uniform quantization (256-color palette) + LZW compression, Input channels should be 3 (RGB) or 4 (RGBA, alpha ignored) - 128
- 129
///| - 130
/// 参数 Parameters: - 131
/// - `img` - 输入图像 Input image - 132
/// - 133
/// 返回 Return: - 134
/// - GIF89a 字节流 GIF89a byte stream - 135
/// - 136
/// 错误 Errors: - 137
/// - `LoadError::EncodeFailed` - channels 不为 3 或 4 Channels not 3 or 4 - 138
/// - 139
/// ```mbt check - 140
/// test "doc_encode_gif_pure" { - 141
/// try { - 142
/// let data = Bytes::from_array([b'\xff', b'\x00', b'\x00']) - 143
/// let img = @types.Image::{ width: 1, height: 1, channels: 3, data, } - 144
/// let encoded = @codec.encode_gif_pure(img) - 145
/// assert_true(encoded.length() > 0) - 146
/// } catch { - 147
/// _ => assert_true(false) - 148
/// } - 149
/// } - 150
/// ``` - 151
pub fn encode_gif_pure(img : @types.Image) -> Bytes raise @types.LoadError { - 152●
if img.channels != 3 && img.channels != 4 { - 153●
raise @types.LoadError::EncodeFailed( - 154
"GIF 编码需要 channels 为 3 (RGB) 或 4 (RGBA)", - 155
) - 156
} - 157
let out : Array[Byte] = [] - 158
// GIF89a header - 159●
out.push(b'\x47') // G - 160●
out.push(b'\x49') // I - 161●
out.push(b'\x46') // F - 162●
out.push(b'\x38') // 8 - 163●
out.push(b'\x39') // 9 - 164●
out.push(b'\x61') // a - 165
// Logical Screen Descriptor (7 bytes) - 166●
out.push((img.width & 0xFF).to_byte()) - 167●
out.push(((img.width >> 8) & 0xFF).to_byte()) - 168●
out.push((img.height & 0xFF).to_byte()) - 169●
out.push(((img.height >> 8) & 0xFF).to_byte()) - 170●
out.push(b'\xF7') // packed: global color table = 1, color resolution = 7, sort = 0, size = 7 (256 colors) - 171●
out.push(b'\x00') // background color index - 172●
out.push(b'\x00') // pixel aspect ratio - 173
// Global Color Table (256 * 3 = 768 bytes) - 174●
let palette = build_332_palette() - 175
for i in 0..<768 { - 176●
out.push(palette[i]) - 177
} - 178
// 量化像素 - 179●
let indices : Array[Int32] = Array::make(img.width * img.height, 0) - 180
for y in 0..<img.height { - 181●
for x in 0..<img.width { - 182●
let idx = y * img.width + x - 183●
let r = img.data[idx * img.channels].to_int() - 184●
let g = img.data[idx * img.channels + 1].to_int() - 185●
let b = img.data[idx * img.channels + 2].to_int() - 186●
indices[idx] = quantize_332(r, g, b) - 187
} - 188
} - 189
// Image Descriptor - 190●
out.push(b'\x2C') // Image Separator - 191●
out.push(b'\x00') // left position (LE) - 192●
out.push(b'\x00') - 193●
out.push(b'\x00') // top position (LE) - 194●
out.push(b'\x00') - 195●
out.push((img.width & 0xFF).to_byte()) - 196●
out.push(((img.width >> 8) & 0xFF).to_byte()) - 197●
out.push((img.height & 0xFF).to_byte()) - 198●
out.push(((img.height >> 8) & 0xFF).to_byte()) - 199●
out.push(b'\x00') // packed: no local color table, not interlaced - 200
// LZW Image Data - 201●
out.push(b'\x08') // LZW Minimum Code Size - 202●
let lzw_data = lzw_compress(indices, 8) - 203●
for i in 0..<lzw_data.length() { - 204●
out.push(lzw_data[i]) - 205
} - 206
// Trailer - 207●
out.push(b'\x3B') - 208●
Bytes::from_array(out) - 209
} - 210
- 211
///| - 212
/// 将多帧 Image 编码为动画 GIF89a 字节流。 - 213
/// frames 为帧数组,delays 为每帧延迟(毫秒,将转换为 1/100 秒单位)。 - 214
/// 所有帧应具有相同尺寸和 channels(3 或 4)。 - 215
/// 使用 3-3-2 均匀量化 + LZW 压缩,无限循环。 - 216
pub fn encode_gif_animation_pure( - 217
anim : @types.GifAnimation, - 218
) -> Bytes raise @types.LoadError { - 219●
let frames = anim.frames - 220
let delays = anim.delays - 221●
if frames.length() == 0 { - 222●
raise @types.LoadError::EncodeFailed("GIF 动画至少需要 1 帧") - 223
} - 224●
if frames.length() != delays.length() { - 225●
raise @types.LoadError::EncodeFailed("frames 和 delays 长度不匹配") - 226
} - 227
let first = frames[0] - 228
if first.channels != 3 && first.channels != 4 { - 229●
raise @types.LoadError::EncodeFailed( - 230
"GIF 编码需要 channels 为 3 (RGB) 或 4 (RGBA)", - 231
) - 232
} - 233
let w = first.width - 234
let h = first.height - 235
let out : Array[Byte] = [] - 236
// GIF89a header - 237●
out.push(b'\x47') - 238●
out.push(b'\x49') - 239●
out.push(b'\x46') - 240●
out.push(b'\x38') - 241●
out.push(b'\x39') - 242●
out.push(b'\x61') - 243
// Logical Screen Descriptor - 244●
out.push((w & 0xFF).to_byte()) - 245●
out.push(((w >> 8) & 0xFF).to_byte()) - 246●
out.push((h & 0xFF).to_byte()) - 247●
out.push(((h >> 8) & 0xFF).to_byte()) - 248●
out.push(b'\xF7') // global color table flag, 256 colors - 249●
out.push(b'\x00') // background color index - 250●
out.push(b'\x00') // pixel aspect ratio - 251
// Global Color Table (256 * 3 = 768 bytes) - 252●
let palette = build_332_palette() - 253
for i in 0..<768 { - 254●
out.push(palette[i]) - 255
} - 256
// Netscape Application Extension (无限循环) - 257●
out.push(b'\x21') // Extension Introducer - 258●
out.push(b'\xFF') // Application Extension Label - 259●
out.push(b'\x0B') // Block Size - 260
// "NETSCAPE2.0" - 261●
out.push(b'\x4E') - 262●
out.push(b'\x45') - 263●
out.push(b'\x54') - 264●
out.push(b'\x53') - 265●
out.push(b'\x43') - 266●
out.push(b'\x41') - 267●
out.push(b'\x50') - 268●
out.push(b'\x45') - 269●
out.push(b'\x32') - 270●
out.push(b'\x2E') - 271●
out.push(b'\x30') - 272●
out.push(b'\x03') // Sub-block size - 273●
out.push(b'\x01') // Sub-block ID - 274●
out.push(b'\x00') // loop count LE (0 = infinite) - 275●
out.push(b'\x00') - 276●
out.push(b'\x00') // Block Terminator - 277
// 每帧 - 278●
for fi in 0..<frames.length() { - 279●
let frame = frames[fi] - 280
// Graphic Control Extension - 281●
out.push(b'\x21') // Extension Introducer - 282●
out.push(b'\xF9') // Graphic Control Label - 283●
out.push(b'\x04') // Block Size - 284●
out.push(b'\x00') // packed: disposal=0, no user input, no transparency - 285
// delay in 1/100 seconds (毫秒 / 10) - 286
let delay = delays[fi] / 10 - 287●
out.push((delay & 0xFF).to_byte()) - 288●
out.push(((delay >> 8) & 0xFF).to_byte()) - 289●
out.push(b'\x00') // transparent color index - 290●
out.push(b'\x00') // Block Terminator - 291
// 量化像素 - 292●
let indices : Array[Int32] = Array::make(frame.width * frame.height, 0) - 293
for y in 0..<frame.height { - 294●
for x in 0..<frame.width { - 295●
let idx = y * frame.width + x - 296●
let r = frame.data[idx * frame.channels].to_int() - 297●
let g = frame.data[idx * frame.channels + 1].to_int() - 298●
let b = frame.data[idx * frame.channels + 2].to_int() - 299●
indices[idx] = quantize_332(r, g, b) - 300
} - 301
} - 302
// Image Descriptor - 303●
out.push(b'\x2C') // Image Separator - 304●
out.push(b'\x00') // left position LE - 305●
out.push(b'\x00') - 306●
out.push(b'\x00') // top position LE - 307●
out.push(b'\x00') - 308●
out.push((frame.width & 0xFF).to_byte()) - 309●
out.push(((frame.width >> 8) & 0xFF).to_byte()) - 310●
out.push((frame.height & 0xFF).to_byte()) - 311●
out.push(((frame.height >> 8) & 0xFF).to_byte()) - 312●
out.push(b'\x00') // packed: no local color table, not interlaced - 313
// LZW Image Data - 314●
out.push(b'\x08') // LZW Minimum Code Size - 315●
let lzw_data = lzw_compress(indices, 8) - 316●
for i in 0..<lzw_data.length() { - 317●
out.push(lzw_data[i]) - 318
} - 319
} - 320
// Trailer - 321●
out.push(b'\x3B') - 322●
Bytes::from_array(out) - 323
}