image.codec\codec\webp_vp8l_transforms.mbt

90% · 296 / 329 points · 596 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/// # VP8L 通用解码:图像流 + 四种逆变换
  3. 3///
  4. 4/// 按 RFC 9649 §3.5 / §3.6 / §3.7 实现:
  5. 5/// - 图像流:literal / LZ77 / 色彩缓存 / meta 多组前缀码
  6. 6/// - 逆变换:predictor(14 模式)、color transform、subtract-green、color indexing(含像素打包)
  7. 7///
  8. 8/// `decode_webp_vp8l_rfc` 是唯一对外入口,本文件是其实现。
  9. 9
  10. 10// ==================== 图像流解码 ====================
  11. 11
  12. 12///|
  13. 13priv struct Vp8lGroup {
  14. 14 green : HuffmanTree
  15. 15 red : HuffmanTree
  16. 16 blue : HuffmanTree
  17. 17 alpha : HuffmanTree
  18. 18 dist : HuffmanTree
  19. 19}
  20. 20
  21. 21///|
  22. 22fn vp8l_div_round_up(num : Int32, den : Int32) -> Int32 {
  23. 23● (num + den - 1) / den
  24. 24}
  25. 25
  26. 26///|
  27. 27/// 读色彩缓存信息:返回 (code_bits, size),未启用时都返回 0
  28. 28fn vp8l_read_cache_info(
  29. 29 br : BitReader,
  30. 30) -> (Int32, Int32) raise @types.LoadError {
  31. 31● if br.read_bit() == 1 {
  32. 32● let bits = br.read_bits(4)
  33. 33 if bits < 1 || bits > 11 {
  34. 34○ raise @types.LoadError::DecodeFailed(
  35. 35○ "VP8L:色彩缓存位宽非法(" + bits.to_string() + ")",
  36. 36 )
  37. 37 }
  38. 38 (bits, 1 << bits)
  39. 39 } else {
  40. 40● (0, 0)
  41. 41 }
  42. 42}
  43. 43
  44. 44///|
  45. 45fn vp8l_read_group(
  46. 46 br : BitReader,
  47. 47 cache_size : Int32,
  48. 48) -> Vp8lGroup raise @types.LoadError {
  49. 49● let green = vp8l_read_prefix_code(br, 256 + 24 + cache_size)
  50. 50● let red = vp8l_read_prefix_code(br, 256)
  51. 51● let blue = vp8l_read_prefix_code(br, 256)
  52. 52● let alpha = vp8l_read_prefix_code(br, 256)
  53. 53● let dist = vp8l_read_prefix_code(br, 40)
  54. 54 Vp8lGroup::{ green, red, blue, alpha, dist, }
  55. 55}
  56. 56
  57. 57///|
  58. 58/// 通用图像流解码,返回 `width * height` 个 ARGB 像素。
  59. 59///
  60. 60/// `allow_meta = false` 时用于子分辨率图像(变换数据 / 熵图),这类图像没有 meta 多组前缀码。
  61. 61fn vp8l_decode_stream(
  62. 62 br : BitReader,
  63. 63 width : Int32,
  64. 64 height : Int32,
  65. 65 allow_meta : Bool,
  66. 66) -> Array[Int32] raise @types.LoadError {
  67. 67● let (cache_bits, cache_size) = vp8l_read_cache_info(br)
  68. 68 let groups : Array[Vp8lGroup] = []
  69. 69 let meta : Array[Int32] = []
  70. 70 let mut prefix_bits = 0
  71. 71 let mut prefix_w = 0
  72. 72● if allow_meta && br.read_bit() == 1 {
  73. 73○ prefix_bits = br.read_bits(3) + 2
  74. 74○ prefix_w = vp8l_div_round_up(width, 1 << prefix_bits)
  75. 75○ let prefix_h = vp8l_div_round_up(height, 1 << prefix_bits)
  76. 76○ let entropy = vp8l_decode_stream(br, prefix_w, prefix_h, false)
  77. 77 let mut max_meta = 0
  78. 78○ for k in 0..<entropy.length() {
  79. 79○ let code = (entropy[k] >> 8) & 0xFFFF
  80. 80 if code > max_meta {
  81. 81○ max_meta = code
  82. 82 }
  83. 83 }
  84. 84○ for k in 0..<entropy.length() {
  85. 85○ meta.push(entropy[k])
  86. 86 }
  87. 87 for _ in 0..<(max_meta + 1) {
  88. 88○ groups.push(vp8l_read_group(br, cache_size))
  89. 89 }
  90. 90 } else {
  91. 91● groups.push(vp8l_read_group(br, cache_size))
  92. 92 }
  93. 93 let n = width * height
  94. 94● let pixels : Array[Int32] = Array::make(n, 0)
  95. 95● let cache : Array[Int32] = Array::make(cache_size, 0)
  96. 96 let mut i = 0
  97. 97 while i < n {
  98. 98● let x = i % width
  99. 99 let y = i / width
  100. 100 let gi = if prefix_bits > 0 {
  101. 101○ (y >> prefix_bits) * prefix_w + (x >> prefix_bits)
  102. 102 } else {
  103. 103● 0
  104. 104 }
  105. 105● let g = if groups.length() == 0 {
  106. 106○ raise @types.LoadError::DecodeFailed("VP8L:前缀码组缺失")
  107. 107● } else if meta.length() > 0 {
  108. 108○ let mc = (meta[gi] >> 8) & 0xFFFF
  109. 109○ if mc >= groups.length() {
  110. 110○ raise @types.LoadError::DecodeFailed("VP8L:meta 前缀码越界")
  111. 111 }
  112. 112 groups[mc]
  113. 113 } else {
  114. 114● groups[0]
  115. 115 }
  116. 116● let sym = g.green.decode(br)
  117. 117 if sym < 256 {
  118. 118● let r = g.red.decode(br)
  119. 119● let b = g.blue.decode(br)
  120. 120● let a = g.alpha.decode(br)
  121. 121 let argb = (a << 24) | (r << 16) | (sym << 8) | b
  122. 122 pixels[i] = argb
  123. 123 if cache_size > 0 {
  124. 124● cache[vp8l_cache_hash(argb, cache_bits)] = argb
  125. 125 }
  126. 126 i += 1
  127. 127● } else if sym < 280 {
  128. 128● let length = vp8l_prefix_value(br, sym - 256)
  129. 129● let dcode = vp8l_prefix_value(br, g.dist.decode(br))
  130. 130● let d = vp8l_map_distance(dcode, width)
  131. 131 if d <= 0 || i - d < 0 {
  132. 132○ raise @types.LoadError::DecodeFailed(
  133. 133 "VP8L:反向引用距离越界 (i=\{i} d=\{d} dcode=\{dcode} sym=\{sym} len=\{length} w=\{width} h=\{height} cache=\{cache_bits} groups=\{groups.length()})",
  134. 134 )
  135. 135 }
  136. 136 let mut k = 0
  137. 137 while k < length && i < n {
  138. 138● let argb = pixels[i - d]
  139. 139 pixels[i] = argb
  140. 140 if cache_size > 0 {
  141. 141● cache[vp8l_cache_hash(argb, cache_bits)] = argb
  142. 142 }
  143. 143 i += 1
  144. 144 k += 1
  145. 145 }
  146. 146 } else {
  147. 147● if cache_size == 0 {
  148. 148○ raise @types.LoadError::DecodeFailed(
  149. 149 "VP8L:出现色彩缓存索引但未启用缓存",
  150. 150 )
  151. 151 }
  152. 152 let idx = sym - 280
  153. 153 if idx < 0 || idx >= cache_size {
  154. 154○ raise @types.LoadError::DecodeFailed("VP8L:色彩缓存索引越界")
  155. 155 }
  156. 156 pixels[i] = cache[idx]
  157. 157 i += 1
  158. 158 }
  159. 159 }
  160. 160 pixels
  161. 161}
  162. 162
  163. 163// ==================== 逆变换 ====================
  164. 164
  165. 165///|
  166. 166/// 色彩缓存哈希:RFC 9649 §3.6.2.3 的 (0x1e35a7bd * color) >> (32 - bits),
  167. 167/// 按无符号 32 位语义实现(Int32 的算术右移需要补上符号位贡献)。
  168. 168fn vp8l_cache_hash(argb : Int32, bits : Int32) -> Int32 {
  169. 169 // libwebp:((argb * 0x1e35a7bd) & 0xffffffff) >> (32 - bits),即 32 位**无符号**乘法的结果取高 bits 位。
  170. 170 // Int32 乘法天然按 2^32 回绕,但 `>>` 是算术右移,负数会符号扩展;
  171. 171 // 用掩码取低 bits 位即可得到与逻辑右移一致的结果(之前用 "+ (1 << bits)" 修补是错的)。
  172. 172● let prod = argb * 0x1E35A7BD
  173. 173 (prod >> (32 - bits)) & ((1 << bits) - 1)
  174. 174}
  175. 175
  176. 176///|
  177. 177fn vp8l_c1(argb : Int32, shift : Int32) -> Int32 {
  178. 178● (argb >> shift) & 0xFF
  179. 179}
  180. 180
  181. 181///|
  182. 182fn vp8l_avg2(a : Int32, b : Int32) -> Int32 {
  183. 183● ((vp8l_c1(a, 24) + vp8l_c1(b, 24)) >> 1 << 24) |
  184. 184● ((vp8l_c1(a, 16) + vp8l_c1(b, 16)) >> 1 << 16) |
  185. 185● ((vp8l_c1(a, 8) + vp8l_c1(b, 8)) >> 1 << 8) |
  186. 186● ((vp8l_c1(a, 0) + vp8l_c1(b, 0)) >> 1)
  187. 187}
  188. 188
  189. 189///|
  190. 190fn vp8l_clamp8(v : Int32) -> Int32 {
  191. 191● if v < 0 {
  192. 192● 0
  193. 193● } else if v > 255 {
  194. 194● 255
  195. 195 } else {
  196. 196● v
  197. 197 }
  198. 198}
  199. 199
  200. 200///|
  201. 201fn vp8l_clamp_add_full(a : Int32, b : Int32, c : Int32) -> Int32 {
  202. 202● (vp8l_clamp8(vp8l_c1(a, 24) + vp8l_c1(b, 24) - vp8l_c1(c, 24)) << 24) |
  203. 203● (vp8l_clamp8(vp8l_c1(a, 16) + vp8l_c1(b, 16) - vp8l_c1(c, 16)) << 16) |
  204. 204● (vp8l_clamp8(vp8l_c1(a, 8) + vp8l_c1(b, 8) - vp8l_c1(c, 8)) << 8) |
  205. 205● vp8l_clamp8(vp8l_c1(a, 0) + vp8l_c1(b, 0) - vp8l_c1(c, 0))
  206. 206}
  207. 207
  208. 208///|
  209. 209fn vp8l_clamp_add_half(a : Int32, b : Int32) -> Int32 {
  210. 210● (vp8l_clamp8(vp8l_c1(a, 24) + (vp8l_c1(a, 24) - vp8l_c1(b, 24)) / 2) << 24) |
  211. 211● (vp8l_clamp8(vp8l_c1(a, 16) + (vp8l_c1(a, 16) - vp8l_c1(b, 16)) / 2) << 16) |
  212. 212● (vp8l_clamp8(vp8l_c1(a, 8) + (vp8l_c1(a, 8) - vp8l_c1(b, 8)) / 2) << 8) |
  213. 213● vp8l_clamp8(vp8l_c1(a, 0) + (vp8l_c1(a, 0) - vp8l_c1(b, 0)) / 2)
  214. 214}
  215. 215
  216. 216///|
  217. 217fn vp8l_abs32(v : Int32) -> Int32 {
  218. 218● if v < 0 {
  219. 219● -v
  220. 220 } else {
  221. 221● v
  222. 222 }
  223. 223}
  224. 224
  225. 225///|
  226. 226
  227. 227///|
  228. 228/// Predictor 11 的 Select(RFC §3.5.1 / libwebp `Select(top, left, top_left)`):
  229. 229/// |top-top_left| <= |left-top_left| 时取 top,否则取 left。
  230. 230/// 早期实现把比较方向写反,导致任何用到模式 11 的块像素全错。
  231. 231/// RFC 9649 §3.5.1 的 Select(L, T, TL):先算估计值 p = L + T - TL(逐通道、不裁剪),
  232. 232/// 再看 L 与 T 谁离 p 更近(曼哈顿距离 4 通道求和),返回更近的那个。
  233. 233/// 之前写成"比较 |L-TL| 与 |T-TL|"是错的,会让所有用到模式 11 的块整体偏色。
  234. 234fn vp8l_select(l : Int32, t : Int32, tl : Int32) -> Int32 {
  235. 235● let la = vp8l_c1(l, 24)
  236. 236● let lr = vp8l_c1(l, 16)
  237. 237● let lg = vp8l_c1(l, 8)
  238. 238● let lb = vp8l_c1(l, 0)
  239. 239● let ta = vp8l_c1(t, 24)
  240. 240● let tr = vp8l_c1(t, 16)
  241. 241● let tg = vp8l_c1(t, 8)
  242. 242● let tb = vp8l_c1(t, 0)
  243. 243● let tla = vp8l_c1(tl, 24)
  244. 244● let tlr = vp8l_c1(tl, 16)
  245. 245● let tlg = vp8l_c1(tl, 8)
  246. 246● let tlb = vp8l_c1(tl, 0)
  247. 247 let pa = la + ta - tla
  248. 248 let pr = lr + tr - tlr
  249. 249 let pg = lg + tg - tlg
  250. 250 let pb = lb + tb - tlb
  251. 251● let dist_l = vp8l_abs32(pa - la) +
  252. 252● vp8l_abs32(pr - lr) +
  253. 253● vp8l_abs32(pg - lg) +
  254. 254● vp8l_abs32(pb - lb)
  255. 255● let dist_t = vp8l_abs32(pa - ta) +
  256. 256● vp8l_abs32(pr - tr) +
  257. 257● vp8l_abs32(pg - tg) +
  258. 258● vp8l_abs32(pb - tb)
  259. 259 if dist_l < dist_t {
  260. 260● l
  261. 261 } else {
  262. 262● t
  263. 263 }
  264. 264}
  265. 265
  266. 266///|
  267. 267/// predictor 逆变换:按 16² 块模式重建(RFC §3.5.1)
  268. 268fn vp8l_inverse_predictor(
  269. 269 pixels : Array[Int32],
  270. 270 width : Int32,
  271. 271 height : Int32,
  272. 272 modes : Array[Int32],
  273. 273 block_bits : Int32,
  274. 274 mode_width : Int32,
  275. 275) -> Unit {
  276. 276● for y in 0..<height {
  277. 277● for x in 0..<width {
  278. 278● let i = y * width + x
  279. 279 let residual = pixels[i]
  280. 280● let left = if x > 0 { pixels[i - 1] } else { 0 }
  281. 281● let top = if y > 0 { pixels[i - width] } else { 0 }
  282. 282● let topleft = if x > 0 && y > 0 { pixels[i - width - 1] } else { 0 }
  283. 283 let topright = if y > 0 {
  284. 284● if x + 1 < width {
  285. 285● pixels[i - width + 1]
  286. 286 } else {
  287. 287● pixels[i - x] // 同行的最左像素
  288. 288 }
  289. 289 } else {
  290. 290● 0
  291. 291 }
  292. 292 let mut pred = 0xFF000000
  293. 293 if y == 0 && x > 0 {
  294. 294● pred = left
  295. 295● } else if x == 0 && y > 0 {
  296. 296● pred = top
  297. 297● } else if y > 0 && x > 0 {
  298. 298● let mi = (y >> block_bits) * mode_width + (x >> block_bits)
  299. 299● let mode = if mi < modes.length() { (modes[mi] >> 8) & 0xFF } else { 0 }
  300. 300● pred = match mode {
  301. 301● 0 => 0xFF000000
  302. 302● 1 => left
  303. 303● 2 => top
  304. 304● 3 => topright
  305. 305● 4 => topleft
  306. 306● 5 => vp8l_avg2(vp8l_avg2(left, topright), top)
  307. 307● 6 => vp8l_avg2(left, topleft)
  308. 308● 7 => vp8l_avg2(left, top)
  309. 309● 8 => vp8l_avg2(topleft, top)
  310. 310● 9 => vp8l_avg2(top, topright)
  311. 311● 10 => vp8l_avg2(vp8l_avg2(left, topleft), vp8l_avg2(top, topright))
  312. 312● 11 => vp8l_select(left, top, topleft)
  313. 313● 12 => vp8l_clamp_add_full(left, top, topleft)
  314. 314● _ => vp8l_clamp_add_half(vp8l_avg2(left, top), topleft)
  315. 315 }
  316. 316 }
  317. 317● let a = (vp8l_c1(residual, 24) + vp8l_c1(pred, 24)) & 0xFF
  318. 318● let r = (vp8l_c1(residual, 16) + vp8l_c1(pred, 16)) & 0xFF
  319. 319● let g = (vp8l_c1(residual, 8) + vp8l_c1(pred, 8)) & 0xFF
  320. 320● let b = (vp8l_c1(residual, 0) + vp8l_c1(pred, 0)) & 0xFF
  321. 321 pixels[i] = (a << 24) | (r << 16) | (g << 8) | b
  322. 322 }
  323. 323 }
  324. 324}
  325. 325
  326. 326///|
  327. 327/// cross-color 逆变换(RFC §3.5.2)
  328. 328fn vp8l_color_delta(t : Int32, c : Int32) -> Int32 {
  329. 329● let tt = if t >= 128 { t - 256 } else { t }
  330. 330● let cc = if c >= 128 { c - 256 } else { c }
  331. 331 (tt * cc) >> 5
  332. 332}
  333. 333
  334. 334///|
  335. 335fn vp8l_inverse_color_transform(
  336. 336 pixels : Array[Int32],
  337. 337 width : Int32,
  338. 338 height : Int32,
  339. 339 cte : Array[Int32],
  340. 340 block_bits : Int32,
  341. 341 mode_width : Int32,
  342. 342) -> Unit {
  343. 343● for y in 0..<height {
  344. 344● for x in 0..<width {
  345. 345● let i = y * width + x
  346. 346 let mi = (y >> block_bits) * mode_width + (x >> block_bits)
  347. 347● if mi >= cte.length() {
  348. 348● continue
  349. 349 }
  350. 350 let e = cte[mi]
  351. 351● let green_to_red = vp8l_c1(e, 0)
  352. 352● let green_to_blue = vp8l_c1(e, 8)
  353. 353● let red_to_blue = vp8l_c1(e, 16)
  354. 354 let argb = pixels[i]
  355. 355● let g = vp8l_c1(argb, 8)
  356. 356● let r = (vp8l_c1(argb, 16) + vp8l_color_delta(green_to_red, g)) & 0xFF
  357. 357 let b = (
  358. 358● vp8l_c1(argb, 0) +
  359. 359● vp8l_color_delta(green_to_blue, g) +
  360. 360● vp8l_color_delta(red_to_blue, r)
  361. 361 ) &
  362. 362 0xFF
  363. 363● pixels[i] = (vp8l_c1(argb, 24) << 24) |
  364. 364 (r << 16) |
  365. 365● (vp8l_c1(argb, 8) << 8) |
  366. 366 b
  367. 367 }
  368. 368 }
  369. 369}
  370. 370
  371. 371///|
  372. 372/// color indexing 逆变换:解像素打包 + 调色板查表(RFC §3.5.4)
  373. 373///
  374. 374/// 返回展开后的像素数组,通过 `out_width` 输出新宽度。
  375. 375fn vp8l_inverse_color_indexing(
  376. 376 pixels : Array[Int32],
  377. 377 width : Int32,
  378. 378 height : Int32,
  379. 379 palette : Array[Int32],
  380. 380 width_bits : Int32,
  381. 381 orig_width : Int32,
  382. 382) -> (Array[Int32], Int32) {
  383. 383 // 未打包:逐像素查表
  384. 384● if width_bits == 0 {
  385. 385● let out : Array[Int32] = Array::make(pixels.length(), 0)
  386. 386● for i in 0..<pixels.length() {
  387. 387● let idx = vp8l_c1(pixels[i], 8)
  388. 388● out[i] = if idx < palette.length() { palette[idx] } else { 0 }
  389. 389 }
  390. 390 return (out, width)
  391. 391 }
  392. 392 let bundle = 1 << width_bits // 每个打包像素承载的索引个数:2 / 4 / 8
  393. 393 let bits_per = 8 >> width_bits // 每个索引占的位宽:4 / 2 / 1
  394. 394 let mask = (1 << bits_per) - 1
  395. 395 // 关键:还原宽度是**原图宽**,不是 width * bundle——最后一组可能只用了前几个槽
  396. 396 // (4 像素图 + width_bits=3 时 subsample 宽 1,展开应是 4 而不是 8)。
  397. 397 let out_width = orig_width
  398. 398● let out : Array[Int32] = Array::make(out_width * height, 0)
  399. 399 for y in 0..<height {
  400. 400● for x in 0..<out_width {
  401. 401● let sx = x / bundle
  402. 402 let j = x % bundle
  403. 403● let packed = vp8l_c1(pixels[y * width + sx], 8)
  404. 404 let idx = (packed >> (j * bits_per)) & mask
  405. 405● out[y * out_width + x] = if idx < palette.length() {
  406. 406● palette[idx]
  407. 407 } else {
  408. 408○ 0
  409. 409 }
  410. 410 }
  411. 411 }
  412. 412 (out, out_width)
  413. 413}
  414. 414
  415. 415// ==================== 对外入口 ====================
  416. 416
  417. 417///|
  418. 418/// RFC 合规的 VP8L 解码:图像流(literal / LZ77 / 色彩缓存 / meta 多组)
  419. 419/// + 四类逆变换(predictor / cross-color / subtract-green / color indexing)。
  420. 420///
  421. 421/// 返回 channels = 4(本实现始终输出 RGBA)。
  422. 422pub fn decode_webp_vp8l_rfc(
  423. 423 data : Bytes,
  424. 424) -> @types.Image raise @types.LoadError {
  425. 425● let len = data.length()
  426. 426 if len < 16 {
  427. 427● raise @types.LoadError::DecodeFailed("VP8L:数据过短")
  428. 428 }
  429. 429● if data[0].to_int() != 0x52 || data[8].to_int() != 0x57 {
  430. 430● raise @types.LoadError::DecodeFailed("VP8L:RIFF/WEBP 容器无效")
  431. 431 }
  432. 432● let start = vp8l_find_chunk(data, 0x4C385056)
  433. 433 if start < 0 {
  434. 434● raise @types.LoadError::DecodeFailed("VP8L:未找到 VP8L chunk")
  435. 435 }
  436. 436● if data[start].to_int() != 0x2F {
  437. 437● raise @types.LoadError::DecodeFailed("VP8L:签名不是 0x2F")
  438. 438 }
  439. 439● let br = BitReader::new(data, start + 1)
  440. 440● let width = br.read_bits(14) + 1
  441. 441● let height = br.read_bits(14) + 1
  442. 442● let alpha_used = br.read_bit()
  443. 443● let version = br.read_bits(3)
  444. 444 if width <= 0 || height <= 0 || width > 16384 || height > 16384 {
  445. 445○ raise @types.LoadError::DecodeFailed("VP8L:尺寸无效")
  446. 446 }
  447. 447 if version != 0 {
  448. 448○ raise @types.LoadError::DecodeFailed("VP8L:version 必须为 0")
  449. 449 }
  450. 450 let kinds : Array[Int32] = []
  451. 451 let block_bits : Array[Int32] = []
  452. 452 let mode_widths : Array[Int32] = []
  453. 453 let aux : Array[Array[Int32]] = []
  454. 454 let width_bits : Array[Int32] = []
  455. 455 let pre_widths : Array[Int32] = []
  456. 456 let mut cur_w = width
  457. 457● while br.read_bit() == 1 {
  458. 458● let t = br.read_bits(2)
  459. 459 let pre_w = cur_w
  460. 460 if t == 0 || t == 1 {
  461. 461● let sb = br.read_bits(3) + 2
  462. 462● let mw = vp8l_div_round_up(cur_w, 1 << sb)
  463. 463● let mh = vp8l_div_round_up(height, 1 << sb)
  464. 464● let img = vp8l_decode_stream(br, mw, mh, false)
  465. 465● kinds.push(t)
  466. 466● block_bits.push(sb)
  467. 467● mode_widths.push(mw)
  468. 468● aux.push(img)
  469. 469● width_bits.push(0)
  470. 470● pre_widths.push(pre_w)
  471. 471● } else if t == 2 {
  472. 472● kinds.push(2)
  473. 473● block_bits.push(0)
  474. 474● mode_widths.push(0)
  475. 475● aux.push([])
  476. 476● width_bits.push(0)
  477. 477● pre_widths.push(pre_w)
  478. 478 } else {
  479. 479● let nc = br.read_bits(8) + 1
  480. 480● let table = vp8l_decode_stream(br, nc, 1, false)
  481. 481 for k in 1..<nc {
  482. 482● let prev = table[k - 1]
  483. 483 let cur0 = table[k]
  484. 484● let a = ((vp8l_c1(cur0, 24) + vp8l_c1(prev, 24)) & 0xFF) << 24
  485. 485● let r = ((vp8l_c1(cur0, 16) + vp8l_c1(prev, 16)) & 0xFF) << 16
  486. 486● let g = ((vp8l_c1(cur0, 8) + vp8l_c1(prev, 8)) & 0xFF) << 8
  487. 487● let b = (vp8l_c1(cur0, 0) + vp8l_c1(prev, 0)) & 0xFF
  488. 488 table[k] = a | r | g | b
  489. 489 }
  490. 490 let wb = if nc <= 2 {
  491. 491● 3
  492. 492○ } else if nc <= 4 {
  493. 493○ 2
  494. 494○ } else if nc <= 16 {
  495. 495○ 1
  496. 496 } else {
  497. 497○ 0
  498. 498 }
  499. 499● kinds.push(3)
  500. 500● block_bits.push(0)
  501. 501● mode_widths.push(0)
  502. 502● aux.push(table)
  503. 503● width_bits.push(wb)
  504. 504● pre_widths.push(pre_w)
  505. 505● cur_w = vp8l_div_round_up(cur_w, 1 << wb)
  506. 506 }
  507. 507 }
  508. 508● let mut pixels = vp8l_decode_stream(br, cur_w, height, true)
  509. 509 let mut w = cur_w
  510. 510● let mut k = kinds.length() - 1
  511. 511 while k >= 0 {
  512. 512● let kind = kinds[k]
  513. 513 if kind == 0 {
  514. 514● vp8l_inverse_predictor(
  515. 515 pixels,
  516. 516 w,
  517. 517 height,
  518. 518 aux[k],
  519. 519 block_bits[k],
  520. 520 mode_widths[k],
  521. 521 )
  522. 522● } else if kind == 1 {
  523. 523● vp8l_inverse_color_transform(
  524. 524 pixels,
  525. 525 w,
  526. 526 height,
  527. 527 aux[k],
  528. 528 block_bits[k],
  529. 529 mode_widths[k],
  530. 530 )
  531. 531● } else if kind == 2 {
  532. 532● for i in 0..<(w * height) {
  533. 533● let argb = pixels[i]
  534. 534● let g = vp8l_c1(argb, 8)
  535. 535● let r = (vp8l_c1(argb, 16) + g) & 0xFF
  536. 536● let b = (vp8l_c1(argb, 0) + g) & 0xFF
  537. 537● pixels[i] = (vp8l_c1(argb, 24) << 24) | (r << 16) | (g << 8) | b
  538. 538 }
  539. 539 } else {
  540. 540● let (out, nw) = vp8l_inverse_color_indexing(
  541. 541 pixels,
  542. 542 w,
  543. 543 height,
  544. 544 aux[k],
  545. 545 width_bits[k],
  546. 546 pre_widths[k],
  547. 547 )
  548. 548 pixels = out
  549. 549 w = nw
  550. 550 }
  551. 551 k -= 1
  552. 552 }
  553. 553 if w != width {
  554. 554○ raise @types.LoadError::DecodeFailed("VP8L:逆变换后宽度未复原")
  555. 555 }
  556. 556 let _ = alpha_used
  557. 557● @types.check_dims(width, height, 4)
  558. 558 let digit = width * height
  559. 559● let out : Array[Byte] = Array::make(digit * 4, b'\x00')
  560. 560 for i in 0..<digit {
  561. 561● let argb = pixels[i]
  562. 562● out[i * 4] = vp8l_c1(argb, 16).to_byte()
  563. 563● out[i * 4 + 1] = vp8l_c1(argb, 8).to_byte()
  564. 564● out[i * 4 + 2] = vp8l_c1(argb, 0).to_byte()
  565. 565● out[i * 4 + 3] = vp8l_c1(argb, 24).to_byte()
  566. 566 }
  567. 567● @types.Image::{ width, height, channels: 4, data: Bytes::from_array(out), }
  568. 568}
  569. 569
  570. 570///|
  571. 571/// WebP 解码入口:按容器里的 chunk 类型分流。
  572. 572///
  573. 573/// - `VP8L` → RFC 合规 VP8L 路径(无损;palette / predictor / cross-color / subtract-green 全支持)
  574. 574/// - `VP8 ` → lossy 有损帧:**明确拒绝** `unsupported_format`
  575. 575///
  576. 576/// 此前这里只走 VP8L,真实 libwebp 产出的 lossy WebP(`VP8 ` chunk)会被判成
  577. 577/// 「未找到 VP8L chunk」——那是误导性的错误信息。
  578. 578///
  579. 579/// 2026-12-02 实测(`scripts/proto/vp8_lossy_probe.py`:5 类内容 × 3 尺寸 × 2 质量
  580. 580/// × libwebp 默认参数 = 30 个样本):把 `VP8 ` chunk 接到 `decode_vp8_frame` 后
  581. 581/// **30/30 不抛错,但像素与 libwebp 解码结果 99–100% 不一致**(最大误差 255)。
  582. 582/// 解码器用的是非标准 16 位 bool 窗口,标准流读到的残差是垃圾——静默全错比报错更糟,
  583. 583/// 所以这里保留拒绝,错误码从 `decode_failed` 改为更准确的 `unsupported_format`。
  584. 584/// 决策与三条路线的成本见 `docs/vp8-lossy-decision.md`。
  585. 585pub fn decode_webp_pure(data : Bytes) -> @types.Image raise @types.LoadError {
  586. 586● if data.length() >= 16 && data[0].to_int() == 0x52 {
  587. 587● let lossy = vp8l_find_chunk(data, 0x20385056)
  588. 588● let lossless = vp8l_find_chunk(data, 0x4C385056)
  589. 589 if lossy >= 0 && lossless < 0 {
  590. 590● raise @types.LoadError::UnsupportedFormat(
  591. 591 "VP8 lossy:解码器只实现 VP8L(无损)。标准 16 位 bool 窗口未实现,接进来会静默输出错误像素,见 docs/vp8-lossy-decision.md",
  592. 592 )
  593. 593 }
  594. 594 }
  595. 595● decode_webp_vp8l_rfc(data)
  596. 596}