image.codec\codec\region_decode.mbt

93.5% · 200 / 214 points · 441 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/// # 区域解码 Region Decode
  3. 3///
  4. 4/// PNG / BMP / QOI 的矩形区域解码:只产出请求的 tile,避免整图输出缓冲。
  5. 5/// PNG 的解压仍走整条 IDAT 流(zlib 无流式接口),但反滤波只保留上一行 + 当前行,
  6. 6/// 输出缓冲按 tile 尺寸分配;BMP 无压缩可直接按行寻址;QOI 顺序解码但只写 tile。
  7. 7// 区域解码:PNG / BMP / QOI
  8. 8// 目标:4096² 只解需要的 tile(输出侧不分配整图)
  9. 9
  10. 10///|
  11. 11/// 校验区域参数:x/y ≥ 0、w/h > 0、x+w ≤ W、y+h ≤ H。
  12. 12fn check_region_bounds(
  13. 13 x : Int32,
  14. 14 y : Int32,
  15. 15 w : Int32,
  16. 16 h : Int32,
  17. 17 img_w : Int32,
  18. 18 img_h : Int32,
  19. 19) -> Unit raise @types.LoadError {
  20. 20● if x < 0 || y < 0 || w <= 0 || h <= 0 {
  21. 21● raise @types.LoadError::DecodeFailed(
  22. 22 "区域参数无效:x/y 不能为负,w/h 必须大于 0",
  23. 23 )
  24. 24 }
  25. 25 if x + w > img_w || y + h > img_h {
  26. 26● raise @types.LoadError::DecodeFailed(
  27. 27 "区域越界:x+w 或 y+h 超出图像尺寸",
  28. 28 )
  29. 29 }
  30. 30}
  31. 31
  32. 32///|
  33. 33/// PNG 区域解码。输出通道数与 `decode_png_pure` 默认一致(gray=1、RGB=3、GA=2、RGBA=4、palette=1)。
  34. 34/// 仅支持 8-bit、非 interlace(与 `decode_png_pure` 相同)。
  35. 35pub fn decode_png_region(
  36. 36 data : Bytes,
  37. 37 x : Int32,
  38. 38 y : Int32,
  39. 39 w : Int32,
  40. 40 h : Int32,
  41. 41) -> @types.Image raise @types.LoadError {
  42. 42● let len = data.length()
  43. 43● if len < 8 || !is_png_signature(data, 0) {
  44. 44● raise @types.LoadError::DecodeFailed("PNG signature 错误")
  45. 45 }
  46. 46 let mut pos = 8
  47. 47 let mut width = 0
  48. 48 let mut height = 0
  49. 49 let mut bit_depth = 0
  50. 50 let mut color_type = 0
  51. 51 let mut interlace = 0
  52. 52 let palette : Array[(Int32, Int32, Int32)] = []
  53. 53 let idat_data : Array[Byte] = []
  54. 54 let mut found_ihdr = false
  55. 55 let mut found_iend = false
  56. 56 while pos < len && !found_iend {
  57. 57● if pos + 8 > len {
  58. 58● raise @types.LoadError::DecodeFailed("PNG chunk 头部过短")
  59. 59 }
  60. 60● let chunk_len = read_u32_be(data, pos)
  61. 61 if chunk_len < 0 {
  62. 62● raise @types.LoadError::DecodeFailed("PNG chunk 长度无效")
  63. 63 }
  64. 64● let chunk_key = read_u32_be(data, pos + 4)
  65. 65 pos += 8
  66. 66 if chunk_len > len - pos {
  67. 67● raise @types.LoadError::DecodeFailed("PNG chunk 数据越界")
  68. 68 }
  69. 69● match chunk_key {
  70. 70● 0x49484452 => {
  71. 71 if chunk_len < 13 {
  72. 72● raise @types.LoadError::DecodeFailed("PNG IHDR 过短")
  73. 73 }
  74. 74● width = read_u32_be(data, pos)
  75. 75● height = read_u32_be(data, pos + 4)
  76. 76● bit_depth = data[pos + 8].to_int()
  77. 77● color_type = data[pos + 9].to_int()
  78. 78● interlace = data[pos + 12].to_int()
  79. 79 found_ihdr = true
  80. 80 }
  81. 81● 0x504C5445 => {
  82. 82 let num_colors = chunk_len / 3
  83. 83 for i in 0..<num_colors {
  84. 84● palette.push(
  85. 85 (
  86. 86● data[pos + i * 3].to_int(),
  87. 87● data[pos + i * 3 + 1].to_int(),
  88. 88● data[pos + i * 3 + 2].to_int(),
  89. 89 ),
  90. 90 )
  91. 91 }
  92. 92 }
  93. 93 0x49444154 =>
  94. 94● for i in 0..<chunk_len {
  95. 95● idat_data.push(data[pos + i])
  96. 96 }
  97. 97● 0x49454E44 => found_iend = true
  98. 98● _ => ()
  99. 99 }
  100. 100 pos += chunk_len + 4
  101. 101 }
  102. 102 if !found_ihdr {
  103. 103● raise @types.LoadError::DecodeFailed("PNG 无 IHDR chunk")
  104. 104 }
  105. 105 if width <= 0 || height <= 0 {
  106. 106● raise @types.LoadError::DecodeFailed("PNG 尺寸无效")
  107. 107 }
  108. 108 if interlace != 0 {
  109. 109○ raise @types.LoadError::DecodeFailed("PNG interlace 不支持")
  110. 110 }
  111. 111 if bit_depth != 8 {
  112. 112● raise @types.LoadError::DecodeFailed("PNG 仅支持 8-bit bit depth")
  113. 113 }
  114. 114● let ch = match png_channels(color_type) {
  115. 115● Some(c) => c
  116. 116● None => raise @types.LoadError::DecodeFailed("PNG 无效 color type")
  117. 117 }
  118. 118● @types.check_dims(width, height, ch)
  119. 119● check_region_bounds(x, y, w, h, width, height)
  120. 120● if color_type == 3 && palette.length() == 0 {
  121. 121● raise @types.LoadError::DecodeFailed("PNG palette 缺失")
  122. 122 }
  123. 123● let raw = @util.zlib_inflate(Bytes::from_array(idat_data))
  124. 124 let bpp = ch
  125. 125 let stride = width * bpp
  126. 126 // 只保留上一行 + 当前行;输出按 tile 分配
  127. 127● let prev : Array[Byte] = Array::make(stride, b'\x00')
  128. 128● let cur : Array[Byte] = Array::make(stride, b'\x00')
  129. 129● let out : Array[Byte] = Array::make(w * h * ch, b'\x00')
  130. 130 let mut raw_pos = 0
  131. 131 for row in 0..<height {
  132. 132● if raw_pos >= raw.length() {
  133. 133● raise @types.LoadError::DecodeFailed("PNG 解压数据过短")
  134. 134 }
  135. 135● let filter_type = raw[raw_pos].to_int()
  136. 136 raw_pos += 1
  137. 137 for i in 0..<stride {
  138. 138● if raw_pos >= raw.length() {
  139. 139● raise @types.LoadError::DecodeFailed("PNG 解压数据过短")
  140. 140 }
  141. 141● let raw_byte = raw[raw_pos].to_int()
  142. 142 raw_pos += 1
  143. 143● let a = if i >= bpp { cur[i - bpp].to_int() } else { 0 }
  144. 144● let b = if row > 0 { prev[i].to_int() } else { 0 }
  145. 145● let c = if i >= bpp && row > 0 { prev[i - bpp].to_int() } else { 0 }
  146. 146● let val = match filter_type {
  147. 147● 0 => raw_byte
  148. 148● 1 => (raw_byte + a) & 0xFF
  149. 149● 2 => (raw_byte + b) & 0xFF
  150. 150● 3 => (raw_byte + (a + b) / 2) & 0xFF
  151. 151● 4 => (raw_byte + paeth_predict(a, b, c)) & 0xFF
  152. 152● _ => raise @types.LoadError::DecodeFailed("PNG 无效 filter type")
  153. 153 }
  154. 154● cur[i] = val.to_byte()
  155. 155 }
  156. 156 if row >= y && row < y + h {
  157. 157● let out_row = row - y
  158. 158 for px in x..<(x + w) {
  159. 159● let (r, g, b, a) = match color_type {
  160. 160● 3 => {
  161. 161● let idx = cur[px].to_int()
  162. 162● if idx >= palette.length() {
  163. 163● raise @types.LoadError::DecodeFailed("PNG palette 索引越界")
  164. 164 }
  165. 165 let (pr, pg, pb) = palette[idx]
  166. 166 (pr, pg, pb, 255)
  167. 167 }
  168. 168● 0 => {
  169. 169● let v = cur[px].to_int()
  170. 170 (v, v, v, 255)
  171. 171 }
  172. 172● 2 => {
  173. 173 let o = px * 3
  174. 174● (cur[o].to_int(), cur[o + 1].to_int(), cur[o + 2].to_int(), 255)
  175. 175 }
  176. 176● 4 => {
  177. 177 let o = px * 2
  178. 178● let v = cur[o].to_int()
  179. 179● (v, v, v, cur[o + 1].to_int())
  180. 180 }
  181. 181● _ => {
  182. 182 let o = px * 4
  183. 183 (
  184. 184● cur[o].to_int(),
  185. 185● cur[o + 1].to_int(),
  186. 186● cur[o + 2].to_int(),
  187. 187● cur[o + 3].to_int(),
  188. 188 )
  189. 189 }
  190. 190 }
  191. 191 let o = (out_row * w + (px - x)) * ch
  192. 192● match ch {
  193. 193● 1 => {
  194. 194 let gray = (r * 299 + g * 587 + b * 114) / 1000
  195. 195● out[o] = gray.to_byte()
  196. 196 }
  197. 197● 2 => {
  198. 198 let gray = (r * 299 + g * 587 + b * 114) / 1000
  199. 199● out[o] = gray.to_byte()
  200. 200● out[o + 1] = a.to_byte()
  201. 201 }
  202. 202● 3 => {
  203. 203● out[o] = r.to_byte()
  204. 204● out[o + 1] = g.to_byte()
  205. 205● out[o + 2] = b.to_byte()
  206. 206 }
  207. 207● _ => {
  208. 208● out[o] = r.to_byte()
  209. 209● out[o + 1] = g.to_byte()
  210. 210● out[o + 2] = b.to_byte()
  211. 211● out[o + 3] = a.to_byte()
  212. 212 }
  213. 213 }
  214. 214 }
  215. 215 }
  216. 216 // 行轮换:cur → prev,cur 重置
  217. 217 for i in 0..<stride {
  218. 218● prev[i] = cur[i]
  219. 219 cur[i] = b'\x00'
  220. 220 }
  221. 221 }
  222. 222 @types.Image::{
  223. 223 width: w,
  224. 224 height: h,
  225. 225 channels: ch,
  226. 226● data: Bytes::from_array(out),
  227. 227 }
  228. 228}
  229. 229
  230. 230///|
  231. 231/// BMP 区域解码。仅支持 BITMAPINFOHEADER + BI_RGB 的 24/32-bit(与 `decode_bmp_pure` 相同)。
  232. 232/// 无压缩格式可按行直接寻址,不分配整图缓冲。
  233. 233pub fn decode_bmp_region(
  234. 234 data : Bytes,
  235. 235 x : Int32,
  236. 236 y : Int32,
  237. 237 w : Int32,
  238. 238 h : Int32,
  239. 239) -> @types.Image raise @types.LoadError {
  240. 240● let len = data.length()
  241. 241 if len < 54 {
  242. 242● raise @types.LoadError::DecodeFailed("BMP 数据过短")
  243. 243 }
  244. 244● if data[0].to_int() != 0x42 || data[1].to_int() != 0x4D {
  245. 245● raise @types.LoadError::DecodeFailed("BMP magic 不匹配")
  246. 246 }
  247. 247● let data_offset = read_u32_le(data, 10)
  248. 248● let dib_size = read_u32_le(data, 14)
  249. 249 if dib_size != 40 {
  250. 250● raise @types.LoadError::DecodeFailed(
  251. 251 "不支持的 BMP DIB 头大小,仅支持 BITMAPINFOHEADER(40 字节)",
  252. 252 )
  253. 253 }
  254. 254● let width = read_u32_le(data, 18)
  255. 255● let height = read_u32_le(data, 22)
  256. 256● let bpp = read_u16_le(data, 28)
  257. 257● let compression = read_u32_le(data, 30)
  258. 258 if bpp != 24 && bpp != 32 {
  259. 259● raise @types.LoadError::DecodeFailed(
  260. 260 "不支持的 BMP 位深,仅支持 24-bit 和 32-bit",
  261. 261 )
  262. 262 }
  263. 263 if compression != 0 {
  264. 264● raise @types.LoadError::DecodeFailed(
  265. 265 "不支持的 BMP 压缩方式,仅支持 BI_RGB(无压缩)",
  266. 266 )
  267. 267 }
  268. 268 if width <= 0 || height == 0 {
  269. 269● raise @types.LoadError::DecodeFailed("BMP 尺寸无效")
  270. 270 }
  271. 271◐ let abs_width = if width < 0 { -width } else { width }
  272. 272● let abs_height = if height < 0 { -height } else { height }
  273. 273 let bottom_up = height > 0
  274. 274 let bytes_per_pixel = bpp / 8
  275. 275 let row_size = (abs_width * bytes_per_pixel + 3) / 4 * 4
  276. 276● @types.check_dims(abs_width, abs_height, bytes_per_pixel)
  277. 277● check_region_bounds(x, y, w, h, abs_width, abs_height)
  278. 278● let out : Array[Byte] = Array::make(w * h * bytes_per_pixel, b'\x00')
  279. 279 for ry in 0..<h {
  280. 280● let out_row = ry
  281. 281● let file_row = if bottom_up { abs_height - 1 - (y + ry) } else { y + ry }
  282. 282 let row_start = data_offset + file_row * row_size
  283. 283 for rx in 0..<w {
  284. 284● let pixel_offset = row_start + (x + rx) * bytes_per_pixel
  285. 285 if pixel_offset + bytes_per_pixel > len {
  286. 286● raise @types.LoadError::DecodeFailed("BMP 像素数据越界")
  287. 287 }
  288. 288● let b = data[pixel_offset].to_int()
  289. 289● let g = data[pixel_offset + 1].to_int()
  290. 290● let r = data[pixel_offset + 2].to_int()
  291. 291 let out_idx = (out_row * w + rx) * bytes_per_pixel
  292. 292● out[out_idx] = r.to_byte()
  293. 293● out[out_idx + 1] = g.to_byte()
  294. 294● out[out_idx + 2] = b.to_byte()
  295. 295 if bytes_per_pixel == 4 {
  296. 296○ out[out_idx + 3] = data[pixel_offset + 3]
  297. 297 }
  298. 298 }
  299. 299 }
  300. 300 @types.Image::{
  301. 301 width: w,
  302. 302 height: h,
  303. 303 channels: bytes_per_pixel,
  304. 304● data: Bytes::from_array(out),
  305. 305 }
  306. 306}
  307. 307
  308. 308///|
  309. 309/// QOI 区域解码。QOI 为顺序码流,仍需从头解码;但输出缓冲只分配 tile,
  310. 310/// 区域外像素只推进状态、不落内存。
  311. 311pub fn decode_qoi_region(
  312. 312 data : Bytes,
  313. 313 x : Int32,
  314. 314 y : Int32,
  315. 315 w : Int32,
  316. 316 h : Int32,
  317. 317) -> @types.Image raise @types.LoadError {
  318. 318● let len = data.length()
  319. 319 if len < 14 {
  320. 320● raise @types.LoadError::DecodeFailed("QOI 数据过短")
  321. 321 }
  322. 322● if data[0].to_int() != 0x71 ||
  323. 323● data[1].to_int() != 0x6F ||
  324. 324● data[2].to_int() != 0x69 ||
  325. 325● data[3].to_int() != 0x66 {
  326. 326● raise @types.LoadError::DecodeFailed("QOI magic 不匹配")
  327. 327 }
  328. 328● let width = (data[4].to_int() << 24) |
  329. 329● (data[5].to_int() << 16) |
  330. 330● (data[6].to_int() << 8) |
  331. 331● data[7].to_int()
  332. 332● let height = (data[8].to_int() << 24) |
  333. 333● (data[9].to_int() << 16) |
  334. 334● (data[10].to_int() << 8) |
  335. 335● data[11].to_int()
  336. 336● let channels = data[12].to_int()
  337. 337 if width <= 0 || height <= 0 {
  338. 338● raise @types.LoadError::DecodeFailed("QOI 尺寸无效")
  339. 339 }
  340. 340● let out_ch = if channels == 3 { 3 } else { 4 }
  341. 341● @types.check_dims(width, height, out_ch)
  342. 342● check_region_bounds(x, y, w, h, width, height)
  343. 343 let pixel_count = width * height
  344. 344● let out : Array[Byte] = Array::make(w * h * out_ch, b'\x00')
  345. 345● let index_r : Array[Int32] = Array::make(64, 0)
  346. 346● let index_g : Array[Int32] = Array::make(64, 0)
  347. 347● let index_b : Array[Int32] = Array::make(64, 0)
  348. 348● let index_a : Array[Int32] = Array::make(64, 0)
  349. 349 let px_r = Ref(0)
  350. 350 let px_g = Ref(0)
  351. 351 let px_b = Ref(0)
  352. 352 let px_a = Ref(255)
  353. 353 let pos = Ref(14)
  354. 354 let pixel_idx = Ref(0)
  355. 355 while pixel_idx.val < pixel_count && pos.val < len {
  356. 356● let tag = data[pos.val].to_int()
  357. 357 pos.val += 1
  358. 358 if tag == 0xFE {
  359. 359● if pos.val + 2 >= len {
  360. 360● raise @types.LoadError::DecodeFailed("QOI 数据截断: OP_RGB")
  361. 361 }
  362. 362● px_r.val = data[pos.val].to_int()
  363. 363● px_g.val = data[pos.val + 1].to_int()
  364. 364● px_b.val = data[pos.val + 2].to_int()
  365. 365 pos.val += 3
  366. 366● } else if tag == 0xFF {
  367. 367● if pos.val + 3 >= len {
  368. 368● raise @types.LoadError::DecodeFailed("QOI 数据截断: OP_RGBA")
  369. 369 }
  370. 370● px_r.val = data[pos.val].to_int()
  371. 371● px_g.val = data[pos.val + 1].to_int()
  372. 372● px_b.val = data[pos.val + 2].to_int()
  373. 373● px_a.val = data[pos.val + 3].to_int()
  374. 374 pos.val += 4
  375. 375● } else if (tag & 0xC0) == 0x00 {
  376. 376○ let idx = tag & 0x3F
  377. 377 px_r.val = index_r[idx]
  378. 378 px_g.val = index_g[idx]
  379. 379 px_b.val = index_b[idx]
  380. 380 px_a.val = index_a[idx]
  381. 381● } else if (tag & 0xC0) == 0x40 {
  382. 382○ px_r.val = (px_r.val + ((tag >> 4) & 0x03) - 2) & 0xFF
  383. 383 px_g.val = (px_g.val + ((tag >> 2) & 0x03) - 2) & 0xFF
  384. 384 px_b.val = (px_b.val + (tag & 0x03) - 2) & 0xFF
  385. 385● } else if (tag & 0xC0) == 0x80 {
  386. 386● if pos.val >= len {
  387. 387● raise @types.LoadError::DecodeFailed("QOI 数据截断: OP_LUMA")
  388. 388 }
  389. 389 let dg = (tag & 0x3F) - 32
  390. 390 px_g.val = (px_g.val + dg) & 0xFF
  391. 391● let b2 = data[pos.val].to_int()
  392. 392 pos.val += 1
  393. 393 let dr_dg = (b2 >> 4) - 8
  394. 394 let db_dg = (b2 & 0x0F) - 8
  395. 395 px_r.val = (px_r.val + dr_dg + dg) & 0xFF
  396. 396 px_b.val = (px_b.val + db_dg + dg) & 0xFF
  397. 397 } else {
  398. 398○ let run = (tag & 0x3F) + 1
  399. 399 for _ in 0..<run {
  400. 400○ if pixel_idx.val < pixel_count {
  401. 401○ let cx = pixel_idx.val % width
  402. 402 let cy = pixel_idx.val / width
  403. 403 if cy >= y && cy < y + h && cx >= x && cx < x + w {
  404. 404○ let o = ((cy - y) * w + (cx - x)) * out_ch
  405. 405○ out[o] = px_r.val.to_byte()
  406. 406○ out[o + 1] = px_g.val.to_byte()
  407. 407○ out[o + 2] = px_b.val.to_byte()
  408. 408 if out_ch == 4 {
  409. 409○ out[o + 3] = px_a.val.to_byte()
  410. 410 }
  411. 411 }
  412. 412 pixel_idx.val += 1
  413. 413 }
  414. 414 }
  415. 415 continue
  416. 416 }
  417. 417 let cx = pixel_idx.val % width
  418. 418 let cy = pixel_idx.val / width
  419. 419 if cy >= y && cy < y + h && cx >= x && cx < x + w {
  420. 420● let o = ((cy - y) * w + (cx - x)) * out_ch
  421. 421● out[o] = px_r.val.to_byte()
  422. 422● out[o + 1] = px_g.val.to_byte()
  423. 423● out[o + 2] = px_b.val.to_byte()
  424. 424 if out_ch == 4 {
  425. 425● out[o + 3] = px_a.val.to_byte()
  426. 426 }
  427. 427 }
  428. 428 pixel_idx.val += 1
  429. 429● let hsh = qoi_hash(px_r.val, px_g.val, px_b.val, px_a.val)
  430. 430 index_r[hsh] = px_r.val
  431. 431 index_g[hsh] = px_g.val
  432. 432 index_b[hsh] = px_b.val
  433. 433 index_a[hsh] = px_a.val
  434. 434 }
  435. 435 @types.Image::{
  436. 436 width: w,
  437. 437 height: h,
  438. 438 channels: out_ch,
  439. 439● data: Bytes::from_array(out),
  440. 440 }
  441. 441}