image.codec\codec\png_decode.mbt

87.6% · 113 / 129 points · 271 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/// # PNG 解码 PNG Decode
  3. 3///
  4. 4/// PNG 图像格式解码 PNG image format decoding
  5. 5// 纯 MoonBit PNG 解码(全目标可用:native/wasm/js)
  6. 6// 依赖 @pure/zlib 进行 IDAT 解压缩
  7. 7// 支持 color type 0/2/3/4/6, bit depth 8/16
  8. 8
  9. 9///|
  10. 10/// PNG 颜色类型对应的通道数
  11. 11fn png_channels(color_type : Int32) -> Int32? {
  12. 12● match color_type {
  13. 13● 0 => Some(1) // gray
  14. 14● 2 => Some(3) // rgb
  15. 15● 3 => Some(1) // palette
  16. 16● 4 => Some(2) // gray + alpha
  17. 17● 6 => Some(4) // rgba
  18. 18● _ => None
  19. 19 }
  20. 20}
  21. 21
  22. 22///|
  23. 23/// Paeth 预测函数
  24. 24fn paeth_predict(a : Int32, b : Int32, c : Int32) -> Int32 {
  25. 25● let p = a + b - c
  26. 26● let pa = (p - a).abs()
  27. 27● let pb = (p - b).abs()
  28. 28● let pc = (p - c).abs()
  29. 29 if pa <= pb && pa <= pc {
  30. 30● a
  31. 31● } else if pb <= pc {
  32. 32● b
  33. 33 } else {
  34. 34● c
  35. 35 }
  36. 36}
  37. 37
  38. 38///|
  39. 39/// PNG 解码(纯 MoonBit,全目标可用)。支持 8-bit gray/RGB/RGBA/gray+alpha/palette。不支持 interlace。req_channels: None=原色(保留 alpha), 1=灰度, 2=灰度+alpha, 3=RGB, 4=RGBA PNG decoding (pure MoonBit, all targets). Supports 8-bit gray/RGB/RGBA/gray+alpha/palette. Does not support interlace. req_channels: None=original (preserve alpha), 1=gray, 2=gray+alpha, 3=RGB, 4=RGBA
  40. 40
  41. 41///|
  42. 42/// ```mbt check
  43. 43/// test "doc_decode_png_pure" {
  44. 44/// try {
  45. 45/// let img = @codec.decode_png_pure(@types.DOC_TEST_PNG_1X1_RGBA)
  46. 46/// assert_eq(img.width, 1)
  47. 47/// assert_eq(img.height, 1)
  48. 48/// assert_eq(img.channels, 4)
  49. 49/// } catch {
  50. 50/// _ => assert_true(false)
  51. 51/// }
  52. 52/// }
  53. 53/// ```
  54. 54pub fn decode_png_pure(
  55. 55 data : Bytes,
  56. 56 req_channels~ : Int32? = None,
  57. 57 deadline~ : @types.Deadline? = None,
  58. 58) -> @types.Image raise @types.LoadError {
  59. 59● let len = data.length()
  60. 60 // 验证 PNG signature
  61. 61● if len < 8 || !is_png_signature(data, 0) {
  62. 62● raise @types.LoadError::DecodeFailed("PNG signature 错误")
  63. 63 }
  64. 64 let mut pos = 8
  65. 65 // 解析 chunks
  66. 66 let mut width = 0
  67. 67 let mut height = 0
  68. 68 let mut bit_depth = 0
  69. 69 let mut color_type = 0
  70. 70 let mut interlace = 0
  71. 71 let palette : Array[(Int32, Int32, Int32)] = []
  72. 72 let idat_data : Array[Byte] = []
  73. 73 let mut found_ihdr = false
  74. 74 let mut found_iend = false
  75. 75 while pos < len && !found_iend {
  76. 76● if pos + 8 > len {
  77. 77● raise @types.LoadError::DecodeFailed("PNG chunk 头部过短")
  78. 78 }
  79. 79● let chunk_len = read_u32_be(data, pos)
  80. 80 if chunk_len < 0 {
  81. 81● raise @types.LoadError::DecodeFailed("PNG chunk 长度无效")
  82. 82 }
  83. 83● let chunk_key = read_u32_be(data, pos + 4)
  84. 84 pos += 8
  85. 85 if chunk_len > len - pos {
  86. 86● raise @types.LoadError::DecodeFailed("PNG chunk 数据越界")
  87. 87 }
  88. 88● match chunk_key {
  89. 89● 0x49484452 => {
  90. 90 // IHDR
  91. 91 if chunk_len < 13 {
  92. 92○ raise @types.LoadError::DecodeFailed("PNG IHDR 过短")
  93. 93 }
  94. 94● width = read_u32_be(data, pos)
  95. 95● height = read_u32_be(data, pos + 4)
  96. 96● bit_depth = data[pos + 8].to_int()
  97. 97● color_type = data[pos + 9].to_int()
  98. 98● interlace = data[pos + 12].to_int()
  99. 99 found_ihdr = true
  100. 100 }
  101. 101○ 0x504C5445 => {
  102. 102 // PLTE
  103. 103 let num_colors = chunk_len / 3
  104. 104 for i in 0..<num_colors {
  105. 105○ palette.push(
  106. 106 (
  107. 107○ data[pos + i * 3].to_int(),
  108. 108○ data[pos + i * 3 + 1].to_int(),
  109. 109○ data[pos + i * 3 + 2].to_int(),
  110. 110 ),
  111. 111 )
  112. 112 }
  113. 113 }
  114. 114 0x49444154 =>
  115. 115 // IDAT
  116. 116● for i in 0..<chunk_len {
  117. 117● idat_data.push(data[pos + i])
  118. 118 }
  119. 119 0x49454E44 =>
  120. 120 // IEND
  121. 121● found_iend = true
  122. 122● _ => ()
  123. 123 }
  124. 124 pos += chunk_len + 4 // skip data + CRC
  125. 125 }
  126. 126 if !found_ihdr {
  127. 127● raise @types.LoadError::DecodeFailed("PNG 无 IHDR chunk")
  128. 128 }
  129. 129 if width <= 0 || height <= 0 {
  130. 130● raise @types.LoadError::DecodeFailed("PNG 尺寸无效")
  131. 131 }
  132. 132 if interlace != 0 {
  133. 133● raise @types.LoadError::DecodeFailed("PNG interlace 不支持")
  134. 134 }
  135. 135 if bit_depth != 8 {
  136. 136● raise @types.LoadError::DecodeFailed("PNG 仅支持 8-bit bit depth")
  137. 137 }
  138. 138● let ch = match png_channels(color_type) {
  139. 139● Some(c) => c
  140. 140● None => raise @types.LoadError::DecodeFailed("PNG 无效 color type")
  141. 141 }
  142. 142● @types.check_dims(width, height, ch)
  143. 143 // zlib inflate IDAT 数据
  144. 144● let raw = @util.zlib_inflate(Bytes::from_array(idat_data), deadline~)
  145. 145 // unfilter scanlines
  146. 146 let bpp = ch // bytes per pixel (8-bit)
  147. 147 let stride = width * bpp
  148. 148● let unfiltered : Array[Byte] = Array::make(height * stride, b'\x00')
  149. 149 let mut raw_pos = 0
  150. 150 for y in 0..<height {
  151. 151● @types.deadline_guard(deadline, "PNG 解码")
  152. 152● if raw_pos >= raw.length() {
  153. 153○ raise @types.LoadError::DecodeFailed("PNG 解压数据过短")
  154. 154 }
  155. 155● let filter_type = raw[raw_pos].to_int()
  156. 156 raw_pos += 1
  157. 157 for x in 0..<stride {
  158. 158● if raw_pos >= raw.length() {
  159. 159○ raise @types.LoadError::DecodeFailed("PNG 解压数据过短")
  160. 160 }
  161. 161● let raw_byte = raw[raw_pos].to_int()
  162. 162 raw_pos += 1
  163. 163 let a = if x >= bpp {
  164. 164● unfiltered[y * stride + x - bpp].to_int()
  165. 165 } else {
  166. 166● 0
  167. 167 }
  168. 168● let b = if y > 0 { unfiltered[(y - 1) * stride + x].to_int() } else { 0 }
  169. 169 let c = if x >= bpp && y > 0 {
  170. 170● unfiltered[(y - 1) * stride + x - bpp].to_int()
  171. 171 } else {
  172. 172● 0
  173. 173 }
  174. 174● let val = match filter_type {
  175. 175● 0 => raw_byte // None
  176. 176● 1 => (raw_byte + a) & 0xFF // Sub
  177. 177● 2 => (raw_byte + b) & 0xFF // Up
  178. 178● 3 => (raw_byte + (a + b) / 2) & 0xFF // Average
  179. 179● 4 => (raw_byte + paeth_predict(a, b, c)) & 0xFF // Paeth
  180. 180○ _ => raise @types.LoadError::DecodeFailed("PNG 无效 filter type")
  181. 181 }
  182. 182● unfiltered[y * stride + x] = val.to_byte()
  183. 183 }
  184. 184 }
  185. 185 // 转换为 Image(保留 alpha,根据 req_channels 决定输出通道数)
  186. 186 let pixel_count = width * height
  187. 187● let out_ch = match req_channels {
  188. 188● Some(n) => n
  189. 189● None => ch // 默认保留原色(含 alpha)
  190. 190 }
  191. 191○ if color_type == 3 && palette.length() == 0 {
  192. 192○ raise @types.LoadError::DecodeFailed("PNG palette 缺失")
  193. 193 }
  194. 194● let out_data : Array[Byte] = Array::make(pixel_count * out_ch, b'\x00')
  195. 195 for i in 0..<pixel_count {
  196. 196● let (r, g, b, a) = match color_type {
  197. 197○ 3 => {
  198. 198 // palette
  199. 199○ let idx = unfiltered[i].to_int()
  200. 200○ if idx >= palette.length() {
  201. 201○ raise @types.LoadError::DecodeFailed("PNG palette 索引越界")
  202. 202 }
  203. 203 let (r, g, b) = palette[idx]
  204. 204 (r, g, b, 255)
  205. 205 }
  206. 206● 0 => {
  207. 207 // gray
  208. 208● let v = unfiltered[i].to_int()
  209. 209 (v, v, v, 255)
  210. 210 }
  211. 211 2 =>
  212. 212 // RGB
  213. 213● (
  214. 214● unfiltered[i * 3].to_int(),
  215. 215● unfiltered[i * 3 + 1].to_int(),
  216. 216● unfiltered[i * 3 + 2].to_int(),
  217. 217 255,
  218. 218 )
  219. 219● 4 => {
  220. 220 // gray + alpha
  221. 221● let v = unfiltered[i * 2].to_int()
  222. 222● let a = unfiltered[i * 2 + 1].to_int()
  223. 223 (v, v, v, a)
  224. 224 }
  225. 225 _ =>
  226. 226 // RGBA
  227. 227● (
  228. 228● unfiltered[i * 4].to_int(),
  229. 229● unfiltered[i * 4 + 1].to_int(),
  230. 230● unfiltered[i * 4 + 2].to_int(),
  231. 231● unfiltered[i * 4 + 3].to_int(),
  232. 232 )
  233. 233 }
  234. 234● let (or, og, ob, oa) = match out_ch {
  235. 235● 1 => {
  236. 236 let gray = (r * 299 + g * 587 + b * 114) / 1000
  237. 237 (gray, gray, gray, 255)
  238. 238 }
  239. 239● 2 => {
  240. 240 let gray = (r * 299 + g * 587 + b * 114) / 1000
  241. 241 (gray, gray, gray, a)
  242. 242 }
  243. 243● 3 => (r, g, b, 255)
  244. 244● _ => (r, g, b, a)
  245. 245 }
  246. 246● match out_ch {
  247. 247● 1 => out_data[i] = or.to_byte()
  248. 248● 2 => {
  249. 249● out_data[i * 2] = or.to_byte()
  250. 250● out_data[i * 2 + 1] = oa.to_byte()
  251. 251 }
  252. 252● 3 => {
  253. 253● out_data[i * 3] = or.to_byte()
  254. 254● out_data[i * 3 + 1] = og.to_byte()
  255. 255● out_data[i * 3 + 2] = ob.to_byte()
  256. 256 }
  257. 257● _ => {
  258. 258● out_data[i * 4] = or.to_byte()
  259. 259● out_data[i * 4 + 1] = og.to_byte()
  260. 260● out_data[i * 4 + 2] = ob.to_byte()
  261. 261● out_data[i * 4 + 3] = oa.to_byte()
  262. 262 }
  263. 263 }
  264. 264 }
  265. 265 @types.Image::{
  266. 266 width,
  267. 267 height,
  268. 268 channels: out_ch,
  269. 269● data: Bytes::from_array(out_data),
  270. 270 }
  271. 271}