image.codec\codec\apng_codec.mbt

92.8% · 192 / 207 points · 379 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/// # APNG 编解码 APNG Codec
  3. 3///
  4. 4/// APNG 动画 PNG 编解码实现
  5. 5/// APNG 动画编解码 Animated PNG encoding/decoding
  6. 6// 纯 MoonBit APNG 编解码(全目标可用:native/wasm/js)
  7. 7// APNG 规范: https://wiki.mozilla.org/APNG_Specification
  8. 8// APNG 是 PNG 的扩展,新增 acTL/fcTL/fdAT chunk
  9. 9// 仅支持全尺寸帧(x_offset=0, y_offset=0, frame_w=width, frame_h=height)
  10. 10
  11. 11///|
  12. 12/// 从 4 字节构造 chunk type 字符串
  13. 13fn apng_chunk_type(data : Bytes, offset : Int32) -> String {
  14. 14● let buf : Array[Byte] = [
  15. 15 data[offset],
  16. 16 data[offset + 1],
  17. 17 data[offset + 2],
  18. 18 data[offset + 3],
  19. 19 ]
  20. 20● @encoding/utf8.decode(Bytes::from_array(buf)) catch {
  21. 21○ _ => "????"
  22. 22 }
  23. 23}
  24. 24
  25. 25///|
  26. 26/// PNG chunk 信息
  27. 27priv struct PngChunk {
  28. 28 chunk_type : String
  29. 29 data_offset : Int32
  30. 30 data_size : Int32
  31. 31}
  32. 32
  33. 33///|
  34. 34/// 解析所有 PNG chunk
  35. 35fn apng_parse_chunks(data : Bytes) -> Array[PngChunk] raise @types.LoadError {
  36. 36● let len = data.length()
  37. 37 if len < 8 {
  38. 38● raise @types.LoadError::DecodeFailed("PNG/APNG 数据过短")
  39. 39 }
  40. 40 // 验证 PNG signature
  41. 41● if !is_png_signature(data, 0) {
  42. 42● raise @types.LoadError::DecodeFailed("PNG signature 错误")
  43. 43 }
  44. 44 let chunks : Array[PngChunk] = []
  45. 45 let mut pos = 8
  46. 46 while pos + 8 <= len {
  47. 47● let chunk_len = read_u32_be(data, pos)
  48. 48● let chunk_type = apng_chunk_type(data, pos + 4)
  49. 49 pos += 8
  50. 50 if chunk_len < 0 || chunk_len > len - pos - 4 {
  51. 51● raise @types.LoadError::DecodeFailed("PNG chunk 数据越界")
  52. 52 }
  53. 53● chunks.push(PngChunk::{
  54. 54 chunk_type,
  55. 55 data_offset: pos,
  56. 56 data_size: chunk_len,
  57. 57 })
  58. 58 pos += chunk_len + 4 // 跳过数据 + CRC
  59. 59 }
  60. 60 chunks
  61. 61}
  62. 62
  63. 63///|
  64. 64/// 从 chunk 数据中提取子字节流
  65. 65fn apng_extract_chunk_data(data : Bytes, chunk : PngChunk) -> Bytes {
  66. 66● let out : Array[Byte] = []
  67. 67 for i in 0..<chunk.data_size {
  68. 68● out.push(data[chunk.data_offset + i])
  69. 69 }
  70. 70● Bytes::from_array(out)
  71. 71}
  72. 72
  73. 73///|
  74. 74/// 构建独立 PNG 文件(signature + IHDR + IDAT + IEND)
  75. 75fn build_standalone_png(ihdr_data : Bytes, idat_data : Bytes) -> Bytes {
  76. 76● let out : Array[Byte] = []
  77. 77 // PNG signature
  78. 78● out.push(b'\x89')
  79. 79● out.push(b'\x50')
  80. 80● out.push(b'\x4E')
  81. 81● out.push(b'\x47')
  82. 82● out.push(b'\x0D')
  83. 83● out.push(b'\x0A')
  84. 84● out.push(b'\x1A')
  85. 85● out.push(b'\x0A')
  86. 86 // IHDR
  87. 87● write_u32_be(out, ihdr_data.length())
  88. 88● out.push(b'\x49')
  89. 89● out.push(b'\x48')
  90. 90● out.push(b'\x44')
  91. 91● out.push(b'\x52')
  92. 92● for i in 0..<ihdr_data.length() {
  93. 93● out.push(ihdr_data[i])
  94. 94 }
  95. 95 // IHDR CRC (simplified: compute over type+data)
  96. 96 let crc_data : Array[Byte] = [b'\x49', b'\x48', b'\x44', b'\x52']
  97. 97● for i in 0..<ihdr_data.length() {
  98. 98● crc_data.push(ihdr_data[i])
  99. 99 }
  100. 100● let ihdr_crc = @util.crc32(Bytes::from_array(crc_data))
  101. 101● write_u32_be(out, ihdr_crc)
  102. 102 // IDAT
  103. 103● write_u32_be(out, idat_data.length())
  104. 104● out.push(b'\x49')
  105. 105● out.push(b'\x44')
  106. 106● out.push(b'\x41')
  107. 107● out.push(b'\x54')
  108. 108● for i in 0..<idat_data.length() {
  109. 109● out.push(idat_data[i])
  110. 110 }
  111. 111 let idat_crc_data : Array[Byte] = [b'\x49', b'\x44', b'\x41', b'\x54']
  112. 112● for i in 0..<idat_data.length() {
  113. 113● idat_crc_data.push(idat_data[i])
  114. 114 }
  115. 115● let idat_crc = @util.crc32(Bytes::from_array(idat_crc_data))
  116. 116● write_u32_be(out, idat_crc)
  117. 117 // IEND
  118. 118● write_u32_be(out, 0)
  119. 119● out.push(b'\x49')
  120. 120● out.push(b'\x45')
  121. 121● out.push(b'\x4E')
  122. 122● out.push(b'\x44')
  123. 123● let iend_crc = @util.crc32(b"\x49\x45\x4E\x44")
  124. 124● write_u32_be(out, iend_crc)
  125. 125● Bytes::from_array(out)
  126. 126}
  127. 127
  128. 128///|
  129. 129/// 解码 APNG 字节流为 PngAnimation
  130. 130/// 如果不是 APNG(无 acTL chunk),则当作单帧 PNG 返回
  131. 131pub fn decode_apng_pure(
  132. 132 data : Bytes,
  133. 133) -> @types.PngAnimation raise @types.LoadError {
  134. 134● let chunks = apng_parse_chunks(data)
  135. 135 // 查找 IHDR
  136. 136 let mut ihdr_data : Bytes = b""
  137. 137 let mut found_ihdr = false
  138. 138● for i in 0..<chunks.length() {
  139. 139● if chunks[i].chunk_type == "IHDR" {
  140. 140● ihdr_data = apng_extract_chunk_data(data, chunks[i])
  141. 141 found_ihdr = true
  142. 142 break
  143. 143 }
  144. 144 }
  145. 145 if !found_ihdr {
  146. 146● raise @types.LoadError::DecodeFailed("PNG/APNG 缺少 IHDR")
  147. 147 }
  148. 148 // 查找 acTL
  149. 149 let mut has_actl = false
  150. 150● for i in 0..<chunks.length() {
  151. 151● if chunks[i].chunk_type == "acTL" {
  152. 152● has_actl = true
  153. 153 break
  154. 154 }
  155. 155 }
  156. 156 if !has_actl {
  157. 157 // 普通 PNG,当作单帧动画
  158. 158● let img = decode_png_pure(data)
  159. 159 return @types.PngAnimation::{ frames: [img], delays: [0], }
  160. 160 }
  161. 161 // APNG: 收集所有帧
  162. 162 let frames : Array[@types.Image] = []
  163. 163 let delays : Array[Int32] = []
  164. 164 // 收集 IDAT 数据(第一帧可能用 IDAT)
  165. 165 let mut idat_data : Bytes = b""
  166. 166 let mut found_idat = false
  167. 167● for i in 0..<chunks.length() {
  168. 168● if chunks[i].chunk_type == "IDAT" {
  169. 169● let chunk_data = apng_extract_chunk_data(data, chunks[i])
  170. 170 if !found_idat {
  171. 171● idat_data = chunk_data
  172. 172 found_idat = true
  173. 173 } else {
  174. 174 // 合并多个 IDAT
  175. 175○ let merged : Array[Byte] = []
  176. 176○ for j in 0..<idat_data.length() {
  177. 177○ merged.push(idat_data[j])
  178. 178 }
  179. 179○ for j in 0..<chunk_data.length() {
  180. 180○ merged.push(chunk_data[j])
  181. 181 }
  182. 182○ idat_data = Bytes::from_array(merged)
  183. 183 }
  184. 184 }
  185. 185 }
  186. 186 // 遍历 chunk,处理 fcTL + IDAT/fdAT
  187. 187 let mut i = 0
  188. 188 let mut first_frame_done = false
  189. 189● while i < chunks.length() {
  190. 190● if chunks[i].chunk_type == "fcTL" {
  191. 191 // 解析 fcTL
  192. 192● let fctl_data = apng_extract_chunk_data(data, chunks[i])
  193. 193 // delay_num (2 bytes at offset 20), delay_den (2 bytes at offset 22)
  194. 194● let delay_num = read_u16_be(fctl_data, 20)
  195. 195● let delay_den = read_u16_be(fctl_data, 22)
  196. 196 let delay_ms = if delay_den == 0 {
  197. 197○ 0
  198. 198 } else {
  199. 199● delay_num * 1000 / delay_den
  200. 200 }
  201. 201 // 查找对应的帧数据(IDAT 或 fdAT)
  202. 202 let mut frame_idat : Bytes = b""
  203. 203 let mut found_frame_data = false
  204. 204 let mut j = i + 1
  205. 205● while j < chunks.length() {
  206. 206● if chunks[j].chunk_type == "IDAT" && !first_frame_done {
  207. 207● frame_idat = idat_data
  208. 208 found_frame_data = true
  209. 209 first_frame_done = true
  210. 210 break
  211. 211● } else if chunks[j].chunk_type == "fdAT" {
  212. 212 // fdAT: 前 4 字节是 seq_num,后面是 IDAT 数据
  213. 213● let fdat_data = apng_extract_chunk_data(data, chunks[j])
  214. 214 let fdat_idat : Array[Byte] = []
  215. 215● for k in 4..<fdat_data.length() {
  216. 216● fdat_idat.push(fdat_data[k])
  217. 217 }
  218. 218● frame_idat = Bytes::from_array(fdat_idat)
  219. 219 found_frame_data = true
  220. 220 break
  221. 221○ } else if chunks[j].chunk_type == "fcTL" {
  222. 222 // 遇到下一个 fcTL,停止
  223. 223○ break
  224. 224 }
  225. 225 j += 1
  226. 226 }
  227. 227 if found_frame_data {
  228. 228● let png = build_standalone_png(ihdr_data, frame_idat)
  229. 229● let img = decode_png_pure(png)
  230. 230● frames.push(img)
  231. 231● delays.push(delay_ms)
  232. 232 }
  233. 233 }
  234. 234 i += 1
  235. 235 }
  236. 236● if frames.length() == 0 {
  237. 237○ raise @types.LoadError::DecodeFailed("APNG 无有效帧")
  238. 238 }
  239. 239 @types.PngAnimation::{ frames, delays, }
  240. 240}
  241. 241
  242. 242///|
  243. 243/// 从 PNG 字节流中提取 IDAT 数据
  244. 244fn extract_idat_from_png(png_data : Bytes) -> Bytes raise @types.LoadError {
  245. 245● let chunks = apng_parse_chunks(png_data)
  246. 246 let idat : Array[Byte] = []
  247. 247● for i in 0..<chunks.length() {
  248. 248● if chunks[i].chunk_type == "IDAT" {
  249. 249● for j in 0..<chunks[i].data_size {
  250. 250● idat.push(png_data[chunks[i].data_offset + j])
  251. 251 }
  252. 252 }
  253. 253 }
  254. 254● Bytes::from_array(idat)
  255. 255}
  256. 256
  257. 257///|
  258. 258/// 从 PNG 字节流中提取 IHDR 数据
  259. 259fn extract_ihdr_from_png(png_data : Bytes) -> Bytes raise @types.LoadError {
  260. 260● let chunks = apng_parse_chunks(png_data)
  261. 261● for i in 0..<chunks.length() {
  262. 262● if chunks[i].chunk_type == "IHDR" {
  263. 263● return apng_extract_chunk_data(png_data, chunks[i])
  264. 264 }
  265. 265 }
  266. 266 raise @types.LoadError::DecodeFailed("PNG 缺少 IHDR")
  267. 267}
  268. 268
  269. 269///|
  270. 270/// 写入 PNG chunk(type + data + CRC)
  271. 271fn apng_write_chunk(
  272. 272 out : Array[Byte],
  273. 273 chunk_type : String,
  274. 274 chunk_data : Bytes,
  275. 275) -> Unit {
  276. 276● write_u32_be(out, chunk_data.length())
  277. 277● let type_bytes = @encoding/utf8.encode(chunk_type)
  278. 278 for i in 0..<4 {
  279. 279● out.push(type_bytes[i])
  280. 280 }
  281. 281● for i in 0..<chunk_data.length() {
  282. 282● out.push(chunk_data[i])
  283. 283 }
  284. 284 // CRC
  285. 285 let crc_data : Array[Byte] = []
  286. 286 for i in 0..<4 {
  287. 287● crc_data.push(type_bytes[i])
  288. 288 }
  289. 289● for i in 0..<chunk_data.length() {
  290. 290● crc_data.push(chunk_data[i])
  291. 291 }
  292. 292● let crc = @util.crc32(Bytes::from_array(crc_data))
  293. 293● write_u32_be(out, crc)
  294. 294}
  295. 295
  296. 296///|
  297. 297/// 将 PngAnimation 编码为 APNG 字节流
  298. 298/// 所有帧必须尺寸相同
  299. 299pub fn encode_apng_pure(
  300. 300 anim : @types.PngAnimation,
  301. 301) -> Bytes raise @types.LoadError {
  302. 302● let num_frames = anim.frames.length()
  303. 303 if num_frames == 0 {
  304. 304● raise @types.LoadError::EncodeFailed("APNG 至少需要一帧")
  305. 305 }
  306. 306 let first = anim.frames[0]
  307. 307 let width = first.width
  308. 308 let height = first.height
  309. 309 let out : Array[Byte] = []
  310. 310 // PNG signature
  311. 311● out.push(b'\x89')
  312. 312● out.push(b'\x50')
  313. 313● out.push(b'\x4E')
  314. 314● out.push(b'\x47')
  315. 315● out.push(b'\x0D')
  316. 316● out.push(b'\x0A')
  317. 317● out.push(b'\x1A')
  318. 318● out.push(b'\x0A')
  319. 319 // 编码第一帧为 PNG,提取 IHDR 和 IDAT
  320. 320● let first_png = encode_png_pure(first)
  321. 321● let ihdr_data = extract_ihdr_from_png(first_png)
  322. 322 // IHDR chunk
  323. 323● apng_write_chunk(out, "IHDR", ihdr_data)
  324. 324 // acTL chunk: num_frames + num_plays(0=无限)
  325. 325 let actl : Array[Byte] = []
  326. 326● write_u32_be(actl, num_frames)
  327. 327● write_u32_be(actl, 0)
  328. 328● apng_write_chunk(out, "acTL", Bytes::from_array(actl))
  329. 329 // 序列号计数器
  330. 330 let mut seq = 0
  331. 331 // 第一帧 fcTL
  332. 332 let fctl1 : Array[Byte] = []
  333. 333● write_u32_be(fctl1, seq) // sequence_number
  334. 334 seq += 1
  335. 335● write_u32_be(fctl1, width) // width
  336. 336● write_u32_be(fctl1, height) // height
  337. 337● write_u32_be(fctl1, 0) // x_offset
  338. 338● write_u32_be(fctl1, 0) // y_offset
  339. 339◐ let delay1 = if anim.delays.length() > 0 { anim.delays[0] } else { 0 }
  340. 340● write_u16_be(fctl1, delay1) // delay_num (ms)
  341. 341● write_u16_be(fctl1, 1000) // delay_den
  342. 342● fctl1.push(b'\x01') // dispose_op = APNG_DISPOSE_OP_BACKGROUND
  343. 343● fctl1.push(b'\x00') // blend_op = APNG_BLEND_OP_SOURCE
  344. 344● apng_write_chunk(out, "fcTL", Bytes::from_array(fctl1))
  345. 345 // 第一帧 IDAT
  346. 346● let first_idat = extract_idat_from_png(first_png)
  347. 347● apng_write_chunk(out, "IDAT", first_idat)
  348. 348 // 后续帧
  349. 349 for i in 1..<num_frames {
  350. 350● let frame = anim.frames[i]
  351. 351● let frame_png = encode_png_pure(frame)
  352. 352● let frame_idat = extract_idat_from_png(frame_png)
  353. 353 // fcTL
  354. 354 let fctl : Array[Byte] = []
  355. 355● write_u32_be(fctl, seq) // sequence_number
  356. 356 seq += 1
  357. 357● write_u32_be(fctl, frame.width)
  358. 358● write_u32_be(fctl, frame.height)
  359. 359● write_u32_be(fctl, 0) // x_offset
  360. 360● write_u32_be(fctl, 0) // y_offset
  361. 361◐ let delay = if i < anim.delays.length() { anim.delays[i] } else { 0 }
  362. 362● write_u16_be(fctl, delay) // delay_num (ms)
  363. 363● write_u16_be(fctl, 1000) // delay_den
  364. 364● fctl.push(b'\x01') // dispose_op
  365. 365● fctl.push(b'\x00') // blend_op
  366. 366● apng_write_chunk(out, "fcTL", Bytes::from_array(fctl))
  367. 367 // fdAT: seq_num + IDAT data
  368. 368 let fdat : Array[Byte] = []
  369. 369● write_u32_be(fdat, seq) // sequence_number
  370. 370 seq += 1
  371. 371● for j in 0..<frame_idat.length() {
  372. 372● fdat.push(frame_idat[j])
  373. 373 }
  374. 374● apng_write_chunk(out, "fdAT", Bytes::from_array(fdat))
  375. 375 }
  376. 376 // IEND
  377. 377● apng_write_chunk(out, "IEND", Bytes::from_array([]))
  378. 378● Bytes::from_array(out)
  379. 379}