image.codec\codec\gif_encode.mbt

100% · 182 / 182 points · 323 lines

Background color reports the state of each line. Underlined characters mark exact instrumented byte offsets; hover them to inspect the visit count.

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