image.codec\codec\webp_vp8l_lz77_encode.mbt

92.7% · 164 / 177 points · 470 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/// # WebP VP8L LZ77 编码器(M2)
  3. 3///
  4. 4/// 与 `webp_vp8l_encode.mbt` 的 literal-only 版相比,多了三件事:
  5. 5/// 1. 贪心 LZ77 匹配(哈希链,最短 3、最长 4096);
  6. 6/// 2. 每幅图按统计频次构建长度受限(≤15 位)的 canonical Huffman 码表;
  7. 7/// 3. 码表按 RFC 9649 §3.7.2.1.2 的"码长码 + 零游程"写法输出。
  8. 8///
  9. 9/// 未实现(M3):subtract-green / predictor / palette 变换、色彩缓存、meta 多组。
  10. 10
  11. 11///|
  12. 12/// 位数反转(写码时用:流里是 canonical 码的 MSB-first 顺序,写入器是 LSB-first)
  13. 13fn vp8l_rev_bits(v : Int32, n : Int32) -> Int32 {
  14. 14● let mut r = 0
  15. 15 for i in 0..<n {
  16. 16● r = r | (((v >> i) & 1) << (n - 1 - i))
  17. 17 }
  18. 18 r
  19. 19}
  20. 20
  21. 21///|
  22. 22/// 由码长表算 canonical 码值表(与解码侧同一规则)
  23. 23fn vp8l_canonical_codes(lens : Array[Int32], alphabet : Int32) -> Array[Int32] {
  24. 24● let codes : Array[Int32] = Array::make(alphabet, 0)
  25. 25 let mut max_len = 0
  26. 26 for i in 0..<alphabet {
  27. 27● if lens[i] > max_len {
  28. 28● max_len = lens[i]
  29. 29 }
  30. 30 }
  31. 31 if max_len == 0 {
  32. 32● return codes
  33. 33 }
  34. 34● let bl_count : Array[Int32] = Array::make(max_len + 1, 0)
  35. 35 for i in 0..<alphabet {
  36. 36● if lens[i] > 0 {
  37. 37● bl_count[lens[i]] += 1
  38. 38 }
  39. 39 }
  40. 40● let next_code : Array[Int32] = Array::make(max_len + 1, 0)
  41. 41 let mut code = 0
  42. 42 for bits in 1..<=max_len {
  43. 43● code = (code + bl_count[bits - 1]) << 1
  44. 44 next_code[bits] = code
  45. 45 }
  46. 46 for s in 0..<alphabet {
  47. 47● let l = lens[s]
  48. 48 if l > 0 {
  49. 49● codes[s] = next_code[l]
  50. 50 next_code[l] += 1
  51. 51 }
  52. 52 }
  53. 53 codes
  54. 54}
  55. 55
  56. 56///|
  57. 57/// 长度受限 Huffman:按频次生成 ≤`max_bits` 位的码长表。
  58. 58///
  59. 59/// 做法:先建普通 Huffman 得深度,再按 JPEG Annex K.3 的"深度钳制 + Kraft 补偿"把
  60. 60/// 超过 `max_bits` 的部分压回,最后按频次降序重新分配长度。
  61. 61fn vp8l_build_lengths(
  62. 62 counts : Array[Int32],
  63. 63 alphabet : Int32,
  64. 64 max_bits : Int32,
  65. 65) -> Array[Int32] {
  66. 66● let lens : Array[Int32] = Array::make(alphabet, 0)
  67. 67 // 收集使用中的符号
  68. 68 let used : Array[Int32] = []
  69. 69 for s in 0..<alphabet {
  70. 70● if counts[s] > 0 {
  71. 71● used.push(s)
  72. 72 }
  73. 73 }
  74. 74● let nu = used.length()
  75. 75 if nu == 0 {
  76. 76● return lens
  77. 77 }
  78. 78 if nu == 1 {
  79. 79● lens[used[0]] = 1
  80. 80 return lens
  81. 81 }
  82. 82 // 普通 Huffman:反复合并两个最小频次,记录每个符号的深度
  83. 83● let weights : Array[Int32] = Array::make(2 * nu - 1, 0)
  84. 84● let parents : Array[Int32] = Array::make(2 * nu - 1, -1)
  85. 85● let symbols : Array[Int32] = Array::make(2 * nu - 1, -1)
  86. 86 for k in 0..<nu {
  87. 87● weights[k] = counts[used[k]]
  88. 88 symbols[k] = used[k]
  89. 89 }
  90. 90 let mut active : Array[Int32] = []
  91. 91 for k in 0..<nu {
  92. 92● active.push(k)
  93. 93 }
  94. 94 let mut next = nu
  95. 95● while active.length() > 1 {
  96. 96 // 找两个最小
  97. 97● let mut a = 0
  98. 98 let mut b = 1
  99. 99 if weights[active[b]] < weights[active[a]] {
  100. 100● let t = a
  101. 101 a = b
  102. 102 b = t
  103. 103 }
  104. 104● for k in 2..<active.length() {
  105. 105● let idx = active[k]
  106. 106 if weights[idx] < weights[active[a]] {
  107. 107● b = a
  108. 108 a = k
  109. 109● } else if weights[idx] < weights[active[b]] {
  110. 110● b = k
  111. 111 }
  112. 112 }
  113. 113 let na = active[a]
  114. 114 let nb = active[b]
  115. 115 let node = next
  116. 116 next += 1
  117. 117 weights[node] = weights[na] + weights[nb]
  118. 118 parents[na] = node
  119. 119 parents[nb] = node
  120. 120● let hi = if a > b { a } else { b }
  121. 121● let lo = if a > b { b } else { a }
  122. 122 let rebuilt : Array[Int32] = []
  123. 123● for k in 0..<active.length() {
  124. 124● if k != lo && k != hi {
  125. 125● rebuilt.push(active[k])
  126. 126 }
  127. 127 }
  128. 128● rebuilt.push(node)
  129. 129 active = rebuilt
  130. 130 }
  131. 131 // 由父链算深度(先钳到 max_bits)
  132. 132● let depths : Array[Int32] = Array::make(nu, 0)
  133. 133 for s in 0..<nu {
  134. 134● let mut d = 0
  135. 135 let mut p = parents[s]
  136. 136 while p >= 0 {
  137. 137● d += 1
  138. 138 p = parents[p]
  139. 139 }
  140. 140◐ depths[s] = if d > max_bits { max_bits } else { d }
  141. 141 }
  142. 142 for s in 0..<nu {
  143. 143● lens[used[s]] = depths[s]
  144. 144 }
  145. 145 // Kraft 补偿:以 2^-max_bits 为单位,K = Σ 2^(max_bits - len) 必须正好等于 2^max_bits
  146. 146 let unit = 1 << max_bits
  147. 147 let mut kraft = 0
  148. 148 for s in 0..<nu {
  149. 149● kraft = kraft + (1 << (max_bits - depths[s]))
  150. 150 }
  151. 151 // 超出:把"最深但仍短于 max_bits"的符号加深一位(优先动低频符号)
  152. 152 while kraft > unit {
  153. 153○ let mut pick = -1
  154. 154 for s in 0..<nu {
  155. 155○ if depths[s] < max_bits {
  156. 156○ if pick < 0 ||
  157. 157 depths[s] > depths[pick] ||
  158. 158 (depths[s] == depths[pick] && counts[used[s]] < counts[used[pick]]) {
  159. 159○ pick = s
  160. 160 }
  161. 161 }
  162. 162 }
  163. 163 if pick < 0 {
  164. 164○ break
  165. 165 }
  166. 166 kraft = kraft - (1 << (max_bits - depths[pick] - 1))
  167. 167 depths[pick] += 1
  168. 168 }
  169. 169 // 不足:把最短的符号缩短一位(同样优先低频)
  170. 170 while kraft < unit {
  171. 171○ let mut pick = -1
  172. 172 for s in 0..<nu {
  173. 173○ if depths[s] > 1 {
  174. 174○ if pick < 0 ||
  175. 175 depths[s] < depths[pick] ||
  176. 176 (depths[s] == depths[pick] && counts[used[s]] < counts[used[pick]]) {
  177. 177○ pick = s
  178. 178 }
  179. 179 }
  180. 180 }
  181. 181 if pick < 0 {
  182. 182○ break
  183. 183 }
  184. 184 depths[pick] -= 1
  185. 185 kraft = kraft + (1 << (max_bits - depths[pick]))
  186. 186 }
  187. 187 // 写回码长表
  188. 188 for s in 0..<nu {
  189. 189● lens[used[s]] = depths[s]
  190. 190 }
  191. 191 lens
  192. 192}
  193. 193
  194. 194///|
  195. 195/// 写一个符号的 canonical 码(位反转后按 LSB-first 写入)
  196. 196fn vp8l_write_code(w : Vp8lBits, code : Int32, len : Int32) -> Unit {
  197. 197● w.write(vp8l_rev_bits(code, len), len)
  198. 198}
  199. 199
  200. 200///|
  201. 201/// 统计长度码 token(0..18)的使用次数,用于构建码长码
  202. 202fn vp8l_count_length_tokens(
  203. 203 lens : Array[Int32],
  204. 204 alphabet : Int32,
  205. 205 out : Array[Int32],
  206. 206) -> Unit {
  207. 207● let mut i = 0
  208. 208 let mut prev = -1
  209. 209 while i < alphabet {
  210. 210● let v = lens[i]
  211. 211 if v == 0 {
  212. 212● let mut z = 0
  213. 213 while i + z < alphabet && lens[i + z] == 0 {
  214. 214● z += 1
  215. 215 }
  216. 216 let mut left = z
  217. 217 while left >= 11 {
  218. 218● let take = if left > 138 { 138 } else { left }
  219. 219 out[18] += 1
  220. 220 left -= take
  221. 221 }
  222. 222 while left >= 3 {
  223. 223◐ let take = if left > 10 { 10 } else { left }
  224. 224 out[17] += 1
  225. 225 left -= take
  226. 226 }
  227. 227 while left > 0 {
  228. 228● out[0] += 1
  229. 229 left -= 1
  230. 230 }
  231. 231 i += z
  232. 232 prev = 0
  233. 233 } else {
  234. 234● let mut run = 1
  235. 235 while i + run < alphabet && lens[i + run] == v {
  236. 236● run += 1
  237. 237 }
  238. 238 out[v] += 1
  239. 239 let mut left = run - 1
  240. 240 i += 1
  241. 241 while left > 0 {
  242. 242● if left >= 3 {
  243. 243● let take = if left > 6 { 6 } else { left }
  244. 244 out[16] += 1
  245. 245 left -= take
  246. 246 i += take
  247. 247 } else {
  248. 248● out[v] += 1
  249. 249 left -= 1
  250. 250 i += 1
  251. 251 }
  252. 252 }
  253. 253 prev = v
  254. 254 }
  255. 255 }
  256. 256 let _ = prev
  257. 257}
  258. 258
  259. 259///|
  260. 260/// 真正把码长表写进流:simple(1/2 个符号)或 normal(码长码 + 零游程)
  261. 261fn vp8l_write_prefix_table(
  262. 262 w : Vp8lBits,
  263. 263 lens : Array[Int32],
  264. 264 alphabet : Int32,
  265. 265) -> Unit {
  266. 266● let used : Array[Int32] = []
  267. 267 for s in 0..<alphabet {
  268. 268● if lens[s] > 0 {
  269. 269● used.push(s)
  270. 270 }
  271. 271 }
  272. 272● if used.length() == 0 {
  273. 273 // 空表按单符号 0 写(解码器视作零比特)
  274. 274● vp8l_write_simple_single(w, 0)
  275. 275 return
  276. 276 }
  277. 277● if used.length() == 1 && used[0] < 256 {
  278. 278● vp8l_write_simple_single(w, used[0])
  279. 279 return
  280. 280 }
  281. 281 let mut all_one_bit = true
  282. 282 for s in used {
  283. 283● if lens[s] != 1 {
  284. 284● all_one_bit = false
  285. 285 }
  286. 286 }
  287. 287● if all_one_bit && used.length() == 2 && used[0] < 256 && used[1] < 256 {
  288. 288 // 双符号 simple 码表:符号必须能塞进 8 位;首个符号按 is_first_8bits 决定 1 位还是 8 位
  289. 289● w.write(1, 1)
  290. 290● w.write(1, 1)
  291. 291 if used[0] > 1 {
  292. 292● w.write(1, 1)
  293. 293● w.write(used[0], 8)
  294. 294 } else {
  295. 295● w.write(0, 1)
  296. 296● w.write(used[0], 1)
  297. 297 }
  298. 298● w.write(used[1], 8)
  299. 299 return
  300. 300 }
  301. 301 // normal:先构建码长码
  302. 302● let tokens : Array[Int32] = Array::make(19, 0)
  303. 303● vp8l_count_length_tokens(lens, alphabet, tokens)
  304. 304● let cl_lens = vp8l_build_lengths(tokens, 19, 7)
  305. 305 // num_code_lengths:覆盖所有非零码长码符号在 order 中的位置
  306. 306 let mut num_code_lengths = 4
  307. 307 for i in 0..<19 {
  308. 308● if cl_lens[vp8l_code_length_order[i]] > 0 && i + 1 > num_code_lengths {
  309. 309● num_code_lengths = i + 1
  310. 310 }
  311. 311 }
  312. 312● w.write(0, 1)
  313. 313● w.write(num_code_lengths - 4, 4)
  314. 314 for i in 0..<num_code_lengths {
  315. 315● w.write(cl_lens[vp8l_code_length_order[i]], 3)
  316. 316 }
  317. 317● w.write(0, 1) // max_symbol = 字母表大小
  318. 318● let cl_codes = vp8l_canonical_codes(cl_lens, 19)
  319. 319 // 按同一规则重新遍历并写 token
  320. 320 let mut i = 0
  321. 321 while i < alphabet {
  322. 322● let v = lens[i]
  323. 323 if v == 0 {
  324. 324● let mut z = 0
  325. 325 while i + z < alphabet && lens[i + z] == 0 {
  326. 326● z += 1
  327. 327 }
  328. 328 let mut left = z
  329. 329 while left >= 11 {
  330. 330● let take = if left > 138 { 138 } else { left }
  331. 331● vp8l_write_code(w, cl_codes[18], cl_lens[18])
  332. 332● w.write(take - 11, 7)
  333. 333 left -= take
  334. 334 }
  335. 335 while left >= 3 {
  336. 336◐ let take = if left > 10 { 10 } else { left }
  337. 337● vp8l_write_code(w, cl_codes[17], cl_lens[17])
  338. 338● w.write(take - 3, 3)
  339. 339 left -= take
  340. 340 }
  341. 341 while left > 0 {
  342. 342● vp8l_write_code(w, cl_codes[0], cl_lens[0])
  343. 343 left -= 1
  344. 344 }
  345. 345 i += z
  346. 346 } else {
  347. 347● let mut run = 1
  348. 348 while i + run < alphabet && lens[i + run] == v {
  349. 349● run += 1
  350. 350 }
  351. 351● vp8l_write_code(w, cl_codes[v], cl_lens[v])
  352. 352 let mut left = run - 1
  353. 353 i += 1
  354. 354 while left > 0 {
  355. 355● if left >= 3 {
  356. 356● let take = if left > 6 { 6 } else { left }
  357. 357● vp8l_write_code(w, cl_codes[16], cl_lens[16])
  358. 358● w.write(take - 3, 2)
  359. 359 left -= take
  360. 360 i += take
  361. 361 } else {
  362. 362● vp8l_write_code(w, cl_codes[v], cl_lens[v])
  363. 363 left -= 1
  364. 364 i += 1
  365. 365 }
  366. 366 }
  367. 367 }
  368. 368 }
  369. 369}
  370. 370
  371. 371///|
  372. 372/// 长度值 → (前缀码, extra 值, extra 位数)
  373. 373fn vp8l_encode_length(len : Int32) -> (Int32, Int32, Int32) {
  374. 374● if len <= 4 {
  375. 375● (len - 1, 0, 0)
  376. 376 } else {
  377. 377● let mut prefix = 0
  378. 378 let mut found = false
  379. 379 let mut p = 4
  380. 380 while !found && p < 24 {
  381. 381● let eb = (p - 2) >> 1
  382. 382 let off = (2 + (p & 1)) << eb
  383. 383 if len >= off + 1 && len <= off + (1 << eb) {
  384. 384● prefix = p
  385. 385 found = true
  386. 386 }
  387. 387 p += 1
  388. 388 }
  389. 389 let eb = (prefix - 2) >> 1
  390. 390 let off = (2 + (prefix & 1)) << eb
  391. 391 (prefix, len - off - 1, eb)
  392. 392 }
  393. 393}
  394. 394
  395. 395///|
  396. 396/// 距离码值 → (距离前缀码 0..39, extra 值, extra 位数)(RFC 9649 §3.6.2.2.1 的 40 项前缀表)
  397. 397fn vp8l_encode_distance(d : Int32) -> (Int32, Int32, Int32) {
  398. 398● if d <= 4 {
  399. 399● (d - 1, 0, 0)
  400. 400 } else {
  401. 401● let mut p = 4
  402. 402 while p < 40 {
  403. 403● let eb = (p - 2) >> 1
  404. 404 let off = (2 + (p & 1)) << eb
  405. 405 if d >= off + 1 && d <= off + (1 << eb) {
  406. 406● return (p, d - off - 1, eb)
  407. 407 }
  408. 408 p += 1
  409. 409 }
  410. 410 // 上限 1048576,调用方已把距离裁到此范围内,这里只作兜底
  411. 411 (39, 0, 0)
  412. 412 }
  413. 413}
  414. 414
  415. 415///|
  416. 416/// 扫描行距离 → 距离码(先查 120 项邻域映射,命中用 1..120,否则 dist + 120)
  417. 417fn vp8l_distance_code(d : Int32, width : Int32) -> Int32 {
  418. 418● for k in 0..<120 {
  419. 419● let xi = vp8l_distance_dx[k].to_int()
  420. 420● let yi = vp8l_distance_dy[k].to_int()
  421. 421 let cand = xi + yi * width
  422. 422 if cand == d && cand >= 1 {
  423. 423● return k + 1
  424. 424 }
  425. 425 }
  426. 426 d + 120
  427. 427}
  428. 428
  429. 429///|
  430. 430/// 判断码表是否只有一个符号(单符号树的符号位宽为 0,编码时不得写任何比特)
  431. 431fn vp8l_is_single(lens : Array[Int32], alphabet : Int32) -> Bool {
  432. 432● let mut count = 0
  433. 433 for i in 0..<alphabet {
  434. 434● if lens[i] > 0 {
  435. 435● count += 1
  436. 436 }
  437. 437 }
  438. 438 count <= 1
  439. 439}
  440. 440
  441. 441///|
  442. 442/// 32 位像素哈希(4096 槽)
  443. 443fn vp8l_hash_pixel(argb : Int32) -> Int32 {
  444. 444● (((argb * 0x1E35A7BD) & 0xFFFFFFFF) >> 20) & 0xFFF
  445. 445}
  446. 446
  447. 447///|
  448. 448/// M2 编码器:贪心 LZ77 + 频次驱动 Huffman(无变换)。
  449. 449///
  450. 450/// 变换版本见 encode_webp_lossless。
  451. 451pub fn encode_webp_vp8l_lz77(
  452. 452 img : @types.Image,
  453. 453) -> Bytes raise @types.LoadError {
  454. 454● let (pixels, w, h) = vp8l_pack_argb(img)
  455. 455 let mut alpha_solid = true
  456. 456● for i in 0..<pixels.length() {
  457. 457● if vp8l_ch(pixels[i], 24) != 255 {
  458. 458● alpha_solid = false
  459. 459 }
  460. 460 }
  461. 461● let bw = Vp8lBits::new()
  462. 462● bw.write(0x2F, 8)
  463. 463● bw.write(w - 1, 14)
  464. 464● bw.write(h - 1, 14)
  465. 465● bw.write(if alpha_solid { 0 } else { 1 }, 1)
  466. 466● bw.write(0, 3)
  467. 467● bw.write(0, 1) // 无变换
  468. 468● vp8l_write_image_stream(bw, pixels, w, true)
  469. 469● vp8l_wrap_riff(bw.finish())
  470. 470}