image.codec\codec\webp_vp8_encode.mbt

94.6% · 229 / 242 points · 1023 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/// # VP8 编码 VP8 Encode
  3. 3///
  4. 4/// VP8 有损编码实现
  5. 5/// VP8 有损编码实现 VP8 lossy encoding implementation
  6. 6// 纯 MoonBit WebP lossy 编码器 (VP8) - 完整实现
  7. 7// 规范: https://datatracker.ietf.org/doc/html/rfc6386
  8. 8// 实现: intra 帧 (key frame), I16x16 DC 预测, 4x4 DCT, 量化, 布尔算术编码
  9. 9
  10. 10///|
  11. 11/// VP8 Bool 编码器(算术编码)
  12. 12priv struct Vp8BoolEncoder {
  13. 13 output : Array[Byte]
  14. 14 mut low : Int32
  15. 15 mut count : Int32
  16. 16 mut range : Int32
  17. 17}
  18. 18
  19. 19///|
  20. 20fn Vp8BoolEncoder::new() -> Vp8BoolEncoder {
  21. 21● Vp8BoolEncoder::{ output: [], low: 0, count: 0, range: 255, }
  22. 22}
  23. 23
  24. 24///|
  25. 25/// 编码一个 bool 值
  26. 26fn Vp8BoolEncoder::encode_bool(
  27. 27 self : Vp8BoolEncoder,
  28. 28 bit : Int32,
  29. 29 probability : Int32,
  30. 30) -> Unit {
  31. 31● let split = 1 + (((self.range - 1) * probability) >> 8)
  32. 32 if bit != 0 {
  33. 33● self.low += split
  34. 34 self.range -= split
  35. 35 } else {
  36. 36● self.range = split
  37. 37 }
  38. 38 while self.range < 128 {
  39. 39● self.shift()
  40. 40 self.range = self.range << 1
  41. 41 }
  42. 42}
  43. 43
  44. 44///|
  45. 45fn Vp8BoolEncoder::shift(self : Vp8BoolEncoder) -> Unit {
  46. 46● let bit = if ((self.low >> 8) & 1) != 0 { 1 } else { 0 }
  47. 47 self.low = (self.low << 1) & 0xFFFF
  48. 48 self.count += 1
  49. 49 if self.count == 8 {
  50. 50● self.output.push(bit.to_byte())
  51. 51 self.count = 0
  52. 52 }
  53. 53}
  54. 54
  55. 55///|
  56. 56/// 编码固定概率的 bool (50%)
  57. 57fn Vp8BoolEncoder::encode_bit(self : Vp8BoolEncoder, bit : Int32) -> Unit {
  58. 58● self.encode_bool(bit, 128)
  59. 59}
  60. 60
  61. 61///|
  62. 62/// 编码无符号整数 (n bits, MSB first)
  63. 63fn Vp8BoolEncoder::encode_uint(
  64. 64 self : Vp8BoolEncoder,
  65. 65 value : Int32,
  66. 66 n : Int32,
  67. 67) -> Unit {
  68. 68● for i in 0..<n {
  69. 69● let bit = (value >> (n - 1 - i)) & 1
  70. 70● self.encode_bit(bit)
  71. 71 }
  72. 72}
  73. 73
  74. 74///|
  75. 75/// 完成编码,刷新剩余 bits
  76. 76fn Vp8BoolEncoder::finish(self : Vp8BoolEncoder) -> Bytes {
  77. 77● for _ in 0..<self.count {
  78. 78● self.output.push(0)
  79. 79 }
  80. 80● Bytes::from_array(self.output)
  81. 81}
  82. 82
  83. 83// ==================== Color Space Conversion ====================
  84. 84
  85. 85///|
  86. 86/// RGB → YUV420 转换
  87. 87fn rgb_to_yuv420(
  88. 88 img : @types.Image,
  89. 89) -> (Array[Int32], Array[Int32], Array[Int32]) {
  90. 90● let w = img.width
  91. 91 let h = img.height
  92. 92 let ch = img.channels
  93. 93● let y_plane : Array[Int32] = Array::make(w * h, 0)
  94. 94 // 色度平面按 ceil(w/2) × ceil(h/2) 分配,索引与步长保持一致;
  95. 95 // 旧实现用 w/2 * (h/2),奇数宽高时会越界(1x1/3x3 触发 PanicError)。
  96. 96 let uv_w = (w + 1) / 2
  97. 97 let uv_h = (h + 1) / 2
  98. 98● let u_plane : Array[Int32] = Array::make(uv_w * uv_h, 128)
  99. 99● let v_plane : Array[Int32] = Array::make(uv_w * uv_h, 128)
  100. 100
  101. 101 for y in 0..<h {
  102. 102● for x in 0..<w {
  103. 103● let idx = (y * w + x) * ch
  104. 104● let r = img.data[idx].to_int()
  105. 105● let g = img.data[idx + 1].to_int()
  106. 106● let b = img.data[idx + 2].to_int()
  107. 107 // Y = 0.299R + 0.587G + 0.114B
  108. 108 let y_val = ((r * 66 + g * 129 + b * 25 + 128) >> 8) + 16
  109. 109 y_plane[y * w + x] = y_val
  110. 110 // U = -0.169R - 0.331G + 0.5B + 128
  111. 111 // V = 0.5R - 0.419G - 0.081B + 128
  112. 112 if x % 2 == 0 && y % 2 == 0 {
  113. 113● let u_val = ((-r * 38 - g * 74 + b * 112 + 128) >> 8) + 128
  114. 114 let v_val = ((r * 112 - g * 94 - b * 18 + 128) >> 8) + 128
  115. 115 let uv_idx = y / 2 * uv_w + x / 2
  116. 116 u_plane[uv_idx] = u_val
  117. 117 v_plane[uv_idx] = v_val
  118. 118 }
  119. 119 }
  120. 120 }
  121. 121
  122. 122 (y_plane, u_plane, v_plane)
  123. 123}
  124. 124
  125. 125// ==================== DCT Transform ====================
  126. 126
  127. 127///|
  128. 128/// VP8 4x4 DCT(正向变换)
  129. 129/// 使用 VP8 特定的变换矩阵(c=85627, c*sqrt(2)=121095)
  130. 130fn vp8_fdct_4x4(block : Array[Int32]) -> Array[Int32] {
  131. 131● let result = Array::make(16, 0)
  132. 132 // 行变换(一维 FDCT)
  133. 133 for i in 0..<4 {
  134. 134● let a0 = block[i * 4]
  135. 135 let a1 = block[i * 4 + 1]
  136. 136 let a2 = block[i * 4 + 2]
  137. 137 let a3 = block[i * 4 + 3]
  138. 138 // VP8 一维 FDCT
  139. 139 let b0 = a0 + a3
  140. 140 let b1 = a1 + a2
  141. 141 let b2 = a1 - a2
  142. 142 let b3 = a0 - a3
  143. 143 result[i * 4] = ((b0 + b1) * 85627) >> 16
  144. 144 result[i * 4 + 1] = (b2 * 121095 + b3 * 85627) >> 16
  145. 145 result[i * 4 + 2] = ((b0 - b1) * 85627) >> 16
  146. 146 result[i * 4 + 3] = (b3 * 121095 - b2 * 85627) >> 16
  147. 147 }
  148. 148 // 列变换(一维 FDCT)
  149. 149● let temp = Array::make(16, 0)
  150. 150 for i in 0..<16 {
  151. 151● temp[i] = result[i]
  152. 152 }
  153. 153 for j in 0..<4 {
  154. 154● let a0 = temp[j]
  155. 155 let a1 = temp[4 + j]
  156. 156 let a2 = temp[8 + j]
  157. 157 let a3 = temp[12 + j]
  158. 158 let b0 = a0 + a3
  159. 159 let b1 = a1 + a2
  160. 160 let b2 = a1 - a2
  161. 161 let b3 = a0 - a3
  162. 162 result[j] = ((b0 + b1) * 85627) >> 16
  163. 163 result[4 + j] = (b2 * 121095 + b3 * 85627) >> 16
  164. 164 result[8 + j] = ((b0 - b1) * 85627) >> 16
  165. 165 result[12 + j] = (b3 * 121095 - b2 * 85627) >> 16
  166. 166 }
  167. 167 result
  168. 168}
  169. 169
  170. 170///|
  171. 171/// VP8 16x16 WHT(正向 Walsh-Hadamard 变换,用于 DC 系数)
  172. 172fn vp8_fwht_4x4(block : Array[Int32]) -> Array[Int32] {
  173. 173● let result = Array::make(16, 0)
  174. 174 // 行变换
  175. 175 for i in 0..<4 {
  176. 176● let a0 = block[i * 4]
  177. 177 let a1 = block[i * 4 + 1]
  178. 178 let a2 = block[i * 4 + 2]
  179. 179 let a3 = block[i * 4 + 3]
  180. 180 let b0 = a0 + a1
  181. 181 let b1 = a2 + a3
  182. 182 let b2 = a0 - a1
  183. 183 let b3 = a2 - a3
  184. 184 result[i * 4] = b0 + b1
  185. 185 result[i * 4 + 1] = b2 + b3
  186. 186 result[i * 4 + 2] = b2 - b3
  187. 187 result[i * 4 + 3] = b0 - b1
  188. 188 }
  189. 189 // 列变换
  190. 190● let temp = Array::make(16, 0)
  191. 191 for i in 0..<16 {
  192. 192● temp[i] = result[i]
  193. 193 }
  194. 194 for j in 0..<4 {
  195. 195● let a0 = temp[j]
  196. 196 let a1 = temp[4 + j]
  197. 197 let a2 = temp[8 + j]
  198. 198 let a3 = temp[12 + j]
  199. 199 let b0 = a0 + a1
  200. 200 let b1 = a2 + a3
  201. 201 let b2 = a0 - a1
  202. 202 let b3 = a2 - a3
  203. 203 result[j] = (b0 + b1 + 1) >> 1
  204. 204 result[4 + j] = (b2 + b3 + 1) >> 1
  205. 205 result[8 + j] = (b2 - b3 + 1) >> 1
  206. 206 result[12 + j] = (b0 - b1 + 1) >> 1
  207. 207 }
  208. 208 result
  209. 209}
  210. 210
  211. 211// ==================== Quantization ====================
  212. 212
  213. 213///|
  214. 214/// VP8 量化参数
  215. 215priv struct Vp8EncQuantParams {
  216. 216 y_ac : Int32
  217. 217 _y_dc : Int32
  218. 218 _uv_ac : Int32
  219. 219 _uv_dc : Int32
  220. 220}
  221. 221
  222. 222///|
  223. 223/// 根据 quality 计算量化参数
  224. 224fn vp8_calc_quant_params(quality : Int32) -> Vp8EncQuantParams {
  225. 225● let q = ((100 - quality).clamp(min=1, max=99) * 63 / 100).clamp(min=1, max=63)
  226. 226 Vp8EncQuantParams::{ y_ac: q, _y_dc: q, _uv_ac: q, _uv_dc: q, }
  227. 227}
  228. 228
  229. 229///|
  230. 230/// 量化 4x4 块
  231. 231fn vp8_quantize_4x4(coeffs : Array[Int32], quant : Int32) -> Array[Int32] {
  232. 232● let result = Array::make(16, 0)
  233. 233 for i in 0..<16 {
  234. 234● let c = coeffs[i]
  235. 235● if c.abs() < quant / 2 {
  236. 236● result[i] = 0
  237. 237 } else {
  238. 238● result[i] = c / quant
  239. 239 }
  240. 240 }
  241. 241 result
  242. 242}
  243. 243
  244. 244// ==================== Intra Prediction ====================
  245. 245
  246. 246///|
  247. 247/// I16x16 DC 预测(编码器端)
  248. 248fn vp8_predict_i16x16_dc(
  249. 249 y_plane : Array[Int32],
  250. 250 mb_x : Int32,
  251. 251 mb_y : Int32,
  252. 252 width : Int32,
  253. 253 height : Int32,
  254. 254) -> Array[Int32] {
  255. 255● let pred = Array::make(256, 128)
  256. 256 let mut sum = 0
  257. 257 let mut count = 0
  258. 258 // 上方像素
  259. 259 if mb_y > 0 {
  260. 260● for x in 0..<16 {
  261. 261● let px = mb_x * 16 + x
  262. 262 if px < width {
  263. 263● sum += y_plane[(mb_y * 16 - 1) * width + px]
  264. 264 count += 1
  265. 265 }
  266. 266 }
  267. 267 }
  268. 268 // 左方像素
  269. 269 if mb_x > 0 {
  270. 270● for y in 0..<16 {
  271. 271● let py = mb_y * 16 + y
  272. 272 if py < height {
  273. 273● sum += y_plane[py * width + mb_x * 16 - 1]
  274. 274 count += 1
  275. 275 }
  276. 276 }
  277. 277 }
  278. 278● let dc = if count > 0 { (sum + count / 2) / count } else { 128 }
  279. 279 for i in 0..<256 {
  280. 280● pred[i] = dc
  281. 281 }
  282. 282 pred
  283. 283}
  284. 284
  285. 285///|
  286. 286/// I16x16 TrueMotion 预测(编码器端)
  287. 287fn vp8_predict_i16x16_tm(
  288. 288 y_plane : Array[Int32],
  289. 289 mb_x : Int32,
  290. 290 mb_y : Int32,
  291. 291 width : Int32,
  292. 292 height : Int32,
  293. 293) -> Array[Int32] {
  294. 294● let pred = Array::make(256, 128)
  295. 295 // 获取上方像素、左方像素、左上方像素
  296. 296● let above : Array[Int32] = Array::make(16, 128)
  297. 297● let left : Array[Int32] = Array::make(16, 128)
  298. 298 let mut above_left = 128
  299. 299 if mb_y > 0 {
  300. 300● for x in 0..<16 {
  301. 301● let px = mb_x * 16 + x
  302. 302 if px < width {
  303. 303● above[x] = y_plane[(mb_y * 16 - 1) * width + px]
  304. 304 }
  305. 305 }
  306. 306 if mb_x > 0 {
  307. 307● above_left = y_plane[(mb_y * 16 - 1) * width + mb_x * 16 - 1]
  308. 308 }
  309. 309 }
  310. 310 if mb_x > 0 {
  311. 311● for y in 0..<16 {
  312. 312● let py = mb_y * 16 + y
  313. 313 if py < height {
  314. 314● left[y] = y_plane[py * width + mb_x * 16 - 1]
  315. 315 }
  316. 316 }
  317. 317 }
  318. 318 // TrueMotion: P[y][x] = above[x] + left[y] - above_left
  319. 319 for y in 0..<16 {
  320. 320● for x in 0..<16 {
  321. 321● let mut val = above[x] + left[y] - above_left
  322. 322 if val < 0 {
  323. 323○ val = 0
  324. 324 }
  325. 325 if val > 255 {
  326. 326● val = 255
  327. 327 }
  328. 328 pred[y * 16 + x] = val
  329. 329 }
  330. 330 }
  331. 331 pred
  332. 332}
  333. 333
  334. 334///|
  335. 335/// I16x16 水平预测(编码器端)
  336. 336fn vp8_predict_i16x16_h(
  337. 337 y_plane : Array[Int32],
  338. 338 mb_x : Int32,
  339. 339 mb_y : Int32,
  340. 340 width : Int32,
  341. 341 height : Int32,
  342. 342) -> Array[Int32] {
  343. 343● let pred = Array::make(256, 128)
  344. 344 if mb_x > 0 {
  345. 345● for y in 0..<16 {
  346. 346● let py = mb_y * 16 + y
  347. 347 if py < height {
  348. 348● let left_val = y_plane[py * width + mb_x * 16 - 1]
  349. 349 for x in 0..<16 {
  350. 350● pred[y * 16 + x] = left_val
  351. 351 }
  352. 352 }
  353. 353 }
  354. 354 }
  355. 355 pred
  356. 356}
  357. 357
  358. 358///|
  359. 359/// I16x16 垂直预测(编码器端)
  360. 360fn vp8_predict_i16x16_v(
  361. 361 y_plane : Array[Int32],
  362. 362 mb_x : Int32,
  363. 363 mb_y : Int32,
  364. 364 width : Int32,
  365. 365 height : Int32,
  366. 366) -> Array[Int32] {
  367. 367● ignore(height)
  368. 368● let pred = Array::make(256, 128)
  369. 369 if mb_y > 0 {
  370. 370● for x in 0..<16 {
  371. 371● let px = mb_x * 16 + x
  372. 372 if px < width {
  373. 373● let above_val = y_plane[(mb_y * 16 - 1) * width + px]
  374. 374 for y in 0..<16 {
  375. 375● pred[y * 16 + x] = above_val
  376. 376 }
  377. 377 }
  378. 378 }
  379. 379 }
  380. 380 pred
  381. 381}
  382. 382
  383. 383///|
  384. 384/// I16x16 预测模式枚举
  385. 385priv enum Vp8I16x16PredMode {
  386. 386 I16x16DcPred
  387. 387 I16x16TrueMotionPred
  388. 388 I16x16HPred
  389. 389 I16x16VPred
  390. 390}
  391. 391
  392. 392///|
  393. 393/// 选择最佳 I16x16 预测模式(基于 SAD 代价)
  394. 394fn vp8_select_i16x16_mode(
  395. 395 y_plane : Array[Int32],
  396. 396 mb_x : Int32,
  397. 397 mb_y : Int32,
  398. 398 width : Int32,
  399. 399 height : Int32,
  400. 400) -> Vp8I16x16PredMode {
  401. 401 // 计算每种预测模式的 SAD(Sum of Absolute Differences)
  402. 402● let modes = [
  403. 403 Vp8I16x16PredMode::I16x16DcPred,
  404. 404 Vp8I16x16PredMode::I16x16TrueMotionPred,
  405. 405 Vp8I16x16PredMode::I16x16HPred,
  406. 406 Vp8I16x16PredMode::I16x16VPred,
  407. 407 ]
  408. 408 let mut best_mode = Vp8I16x16PredMode::I16x16DcPred
  409. 409 let mut best_sad = 1000000
  410. 410 for mode in modes {
  411. 411● let pred = match mode {
  412. 412 Vp8I16x16PredMode::I16x16DcPred =>
  413. 413● vp8_predict_i16x16_dc(y_plane, mb_x, mb_y, width, height)
  414. 414 Vp8I16x16PredMode::I16x16TrueMotionPred =>
  415. 415● vp8_predict_i16x16_tm(y_plane, mb_x, mb_y, width, height)
  416. 416 Vp8I16x16PredMode::I16x16HPred =>
  417. 417● vp8_predict_i16x16_h(y_plane, mb_x, mb_y, width, height)
  418. 418 Vp8I16x16PredMode::I16x16VPred =>
  419. 419● vp8_predict_i16x16_v(y_plane, mb_x, mb_y, width, height)
  420. 420 }
  421. 421 // 计算 SAD
  422. 422 let mut sad = 0
  423. 423 for y in 0..<16 {
  424. 424● for x in 0..<16 {
  425. 425● let px = mb_x * 16 + x
  426. 426 let py = mb_y * 16 + y
  427. 427 if px < width && py < height {
  428. 428● let orig = y_plane[py * width + px]
  429. 429 let p = pred[y * 16 + x]
  430. 430● sad += (orig - p).abs()
  431. 431 }
  432. 432 }
  433. 433 }
  434. 434 if sad < best_sad {
  435. 435● best_sad = sad
  436. 436 best_mode = mode
  437. 437 }
  438. 438 }
  439. 439 best_mode
  440. 440}
  441. 441
  442. 442///|
  443. 443/// 根据预测模式获取预测像素
  444. 444fn vp8_get_i16x16_prediction(
  445. 445 mode : Vp8I16x16PredMode,
  446. 446 y_plane : Array[Int32],
  447. 447 mb_x : Int32,
  448. 448 mb_y : Int32,
  449. 449 width : Int32,
  450. 450 height : Int32,
  451. 451) -> Array[Int32] {
  452. 452● match mode {
  453. 453 Vp8I16x16PredMode::I16x16DcPred =>
  454. 454● vp8_predict_i16x16_dc(y_plane, mb_x, mb_y, width, height)
  455. 455 Vp8I16x16PredMode::I16x16TrueMotionPred =>
  456. 456● vp8_predict_i16x16_tm(y_plane, mb_x, mb_y, width, height)
  457. 457 Vp8I16x16PredMode::I16x16HPred =>
  458. 458○ vp8_predict_i16x16_h(y_plane, mb_x, mb_y, width, height)
  459. 459 Vp8I16x16PredMode::I16x16VPred =>
  460. 460○ vp8_predict_i16x16_v(y_plane, mb_x, mb_y, width, height)
  461. 461 }
  462. 462}
  463. 463
  464. 464// ==================== Token Encoding ====================
  465. 465
  466. 466///|
  467. 467/// 编码一个 4x4 块的系数(简化版,使用固定概率)
  468. 468fn vp8_encode_block_tokens(
  469. 469 enc : Vp8BoolEncoder,
  470. 470 coeffs : Array[Int32],
  471. 471 is_dc : Bool,
  472. 472) -> Unit {
  473. 473● ignore(is_dc)
  474. 474 // zig-zag 顺序
  475. 475 let zigzag = [0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15]
  476. 476 let mut eob = false
  477. 477 for i in 0..<16 {
  478. 478● if eob {
  479. 479● break
  480. 480 }
  481. 481 let pos = zigzag[i]
  482. 482 let c = coeffs[pos]
  483. 483 if c == 0 {
  484. 484 // 零系数
  485. 485● if i > 0 {
  486. 486 // 检查是否是 EOB
  487. 487● let mut has_nonzero = false
  488. 488 for j in (i + 1)..<16 {
  489. 489● if coeffs[zigzag[j]] != 0 {
  490. 490● has_nonzero = true
  491. 491 break
  492. 492 }
  493. 493 }
  494. 494 if !has_nonzero {
  495. 495● enc.encode_bool(1, 100) // EOB
  496. 496 eob = true
  497. 497 } else {
  498. 498● enc.encode_bool(0, 100) // 不是 EOB
  499. 499 }
  500. 500 }
  501. 501● enc.encode_bool(1, 200) // 零系数
  502. 502 } else {
  503. 503 // 非零系数
  504. 504● if i > 0 {
  505. 505● enc.encode_bool(0, 100) // 不是 EOB
  506. 506 }
  507. 507● enc.encode_bool(0, 200) // 非零系数
  508. 508 // 编码值(简化:直接编码绝对值和符号)
  509. 509● let abs_val = c.abs()
  510. 510 if abs_val == 1 {
  511. 511● enc.encode_bool(1, 170) // 值为 1
  512. 512 } else {
  513. 513● enc.encode_bool(0, 170) // 值大于 1
  514. 514 // 编码额外位(简化)
  515. 515 let mut extra = abs_val - 1
  516. 516 while extra > 0 {
  517. 517● enc.encode_bit(1) // 继续
  518. 518 extra = extra >> 1
  519. 519 }
  520. 520● enc.encode_bit(0) // 结束
  521. 521 }
  522. 522 // 符号位
  523. 523 if c < 0 {
  524. 524● enc.encode_bit(1)
  525. 525 } else {
  526. 526● enc.encode_bit(0)
  527. 527 }
  528. 528 }
  529. 529 }
  530. 530● if !eob {
  531. 531 // 没有 EOB,所有系数都非零
  532. 532 }
  533. 533}
  534. 534
  535. 535// ==================== Segment Support (Encoder) ====================
  536. 536
  537. 537///|
  538. 538/// 编码器端 Segment 参数(简化版)
  539. 539priv struct Vp8EncSegmentParams {
  540. 540 segmentation_enabled : Bool
  541. 541 // 每个 segment 的量化器增量(4 个 segment)
  542. 542 quantizer_delta : Array[Int32]
  543. 543 // 每个 segment 的滤波级别增量(4 个 segment)
  544. 544 _filter_level_delta : Array[Int32]
  545. 545 // 每个宏块的 segment ID
  546. 546 segment_id_map : Array[Int32]
  547. 547}
  548. 548
  549. 549///|
  550. 550/// 创建 Segment 参数(基于图像复杂度自动分配 segment)
  551. 551fn vp8_enc_segment_params_new(
  552. 552 y_plane : Array[Int32],
  553. 553 width : Int32,
  554. 554 height : Int32,
  555. 555 base_quant : Int32,
  556. 556) -> Vp8EncSegmentParams {
  557. 557● ignore(base_quant)
  558. 558 let mb_w = (width + 15) / 16
  559. 559 let mb_h = (height + 15) / 16
  560. 560 let total_mbs = mb_w * mb_h
  561. 561● let segment_id_map : Array[Int32] = Array::make(total_mbs, 0)
  562. 562 // 计算每个宏块的复杂度(方差)
  563. 563● let complexities : Array[Int32] = Array::make(total_mbs, 0)
  564. 564 for mb_y in 0..<mb_h {
  565. 565● for mb_x in 0..<mb_w {
  566. 566● let mut sum = 0
  567. 567 let mut sum_sq = 0
  568. 568 let mut count = 0
  569. 569 for y in 0..<16 {
  570. 570● for x in 0..<16 {
  571. 571● let px = mb_x * 16 + x
  572. 572 let py = mb_y * 16 + y
  573. 573 if px < width && py < height {
  574. 574● let val = y_plane[py * width + px]
  575. 575 sum += val
  576. 576 sum_sq += val * val
  577. 577 count += 1
  578. 578 }
  579. 579 }
  580. 580 }
  581. 581 if count > 0 {
  582. 582● let mean = sum / count
  583. 583 let variance = sum_sq / count - mean * mean
  584. 584 complexities[mb_y * mb_w + mb_x] = variance
  585. 585 }
  586. 586 }
  587. 587 }
  588. 588 // 根据复杂度分配 segment(0=低复杂度, 3=高复杂度)
  589. 589 let mut max_complexity = 1
  590. 590 for c in complexities {
  591. 591● if c > max_complexity {
  592. 592● max_complexity = c
  593. 593 }
  594. 594 }
  595. 595 for i in 0..<total_mbs {
  596. 596● let ratio = complexities[i] * 4 / max_complexity
  597. 597● segment_id_map[i] = ratio.clamp(min=0, max=3)
  598. 598 }
  599. 599 // 量化器增量(高复杂度 segment 使用更小的量化增量,即更高质量)
  600. 600 let quantizer_delta = [0, -4, -8, -12]
  601. 601 // 滤波级别增量(高复杂度 segment 使用更强的滤波)
  602. 602 let filter_level_delta = [0, 2, 4, 6]
  603. 603 Vp8EncSegmentParams::{
  604. 604 segmentation_enabled: true,
  605. 605 quantizer_delta,
  606. 606 _filter_level_delta: filter_level_delta,
  607. 607 segment_id_map,
  608. 608 }
  609. 609}
  610. 610
  611. 611///|
  612. 612/// 获取指定宏块的量化参数(考虑 segment)
  613. 613fn vp8_enc_get_mb_quant(
  614. 614 segment : Vp8EncSegmentParams,
  615. 615 mb_x : Int32,
  616. 616 mb_y : Int32,
  617. 617 mb_w : Int32,
  618. 618 base_quant : Int32,
  619. 619) -> Int32 {
  620. 620● if !segment.segmentation_enabled {
  621. 621○ return base_quant
  622. 622 }
  623. 623 let idx = mb_y * mb_w + mb_x
  624. 624● if idx >= 0 && idx < segment.segment_id_map.length() {
  625. 625● let seg_id = segment.segment_id_map[idx]
  626. 626 let delta = segment.quantizer_delta[seg_id]
  627. 627● return (base_quant + delta).clamp(min=1, max=127)
  628. 628 }
  629. 629 base_quant
  630. 630}
  631. 631
  632. 632// ==================== Loop Filter (Encoder) ====================
  633. 633
  634. 634///|
  635. 635/// 编码器端环路滤波(简化版,对重建的 Y 平面进行宏块边界滤波)
  636. 636fn vp8_encoder_loop_filter(
  637. 637 y_plane : Array[Int32],
  638. 638 width : Int32,
  639. 639 height : Int32,
  640. 640 filter_level : Int32,
  641. 641) -> Unit {
  642. 642● if filter_level == 0 {
  643. 643● return
  644. 644 }
  645. 645 let mb_w = (width + 15) / 16
  646. 646 let mb_h = (height + 15) / 16
  647. 647 // 宏块边界垂直滤波
  648. 648 for mb_y in 0..<mb_h {
  649. 649● for mb_x in 1..<mb_w {
  650. 650● for y in 0..<16 {
  651. 651● let py = mb_y * 16 + y
  652. 652 if py >= height {
  653. 653● break
  654. 654 }
  655. 655 let px = mb_x * 16
  656. 656 if px > 0 && px < width {
  657. 657● let idx = py * width + px
  658. 658 let p1 = y_plane[idx - 1]
  659. 659 let p0 = y_plane[idx]
  660. 660 let diff = p0 - p1
  661. 661● if diff.abs() < filter_level {
  662. 662● let adj = diff / 2
  663. 663 y_plane[idx - 1] = p1 + adj
  664. 664 y_plane[idx] = p0 - adj
  665. 665 }
  666. 666 }
  667. 667 }
  668. 668 }
  669. 669 }
  670. 670 // 宏块边界水平滤波
  671. 671 for mb_y in 1..<mb_h {
  672. 672● for mb_x in 0..<mb_w {
  673. 673● for x in 0..<16 {
  674. 674● let px = mb_x * 16 + x
  675. 675 if px >= width {
  676. 676● break
  677. 677 }
  678. 678 let py = mb_y * 16
  679. 679 if py > 0 && py < height {
  680. 680● let idx = py * width + px
  681. 681 let p1 = y_plane[idx - width]
  682. 682 let p0 = y_plane[idx]
  683. 683 let diff = p0 - p1
  684. 684● if diff.abs() < filter_level {
  685. 685● let adj = diff / 2
  686. 686 y_plane[idx - width] = p1 + adj
  687. 687 y_plane[idx] = p0 - adj
  688. 688 }
  689. 689 }
  690. 690 }
  691. 691 }
  692. 692 }
  693. 693}
  694. 694
  695. 695// ==================== Adaptive Probability Model (Encoder) ====================
  696. 696
  697. 697///|
  698. 698/// 编码器端自适应概率模型(简化版)
  699. 699priv struct Vp8EncAdaptiveProbs {
  700. 700 // 系数 token 概率(按位置 0-15,每个位置有 4 个 token 概率)
  701. 701 token_probs : Array[Int32] // 16 * 4 = 64 个概率
  702. 702 // 预测模式概率
  703. 703 pred_mode_probs : Array[Int32] // 4 个预测模式概率
  704. 704 // 统计计数器(用于概率更新)
  705. 705 token_counts : Array[Int32] // 16 * 4 = 64 个计数器
  706. 706 pred_mode_counts : Array[Int32] // 4 个计数器
  707. 707 // 更新间隔
  708. 708 update_interval : Int32
  709. 709 mut blocks_since_update : Int32
  710. 710}
  711. 711
  712. 712///|
  713. 713/// 创建自适应概率模型(初始概率)
  714. 714fn vp8_enc_adaptive_probs_new() -> Vp8EncAdaptiveProbs {
  715. 715 // 初始概率:均匀分布
  716. 716● let token_probs : Array[Int32] = Array::make(64, 128)
  717. 717 let pred_mode_probs : Array[Int32] = [128, 128, 128, 128]
  718. 718● let token_counts : Array[Int32] = Array::make(64, 0)
  719. 719 let pred_mode_counts : Array[Int32] = [0, 0, 0, 0]
  720. 720 Vp8EncAdaptiveProbs::{
  721. 721 token_probs,
  722. 722 pred_mode_probs,
  723. 723 token_counts,
  724. 724 pred_mode_counts,
  725. 725 update_interval: 8,
  726. 726 blocks_since_update: 0,
  727. 727 }
  728. 728}
  729. 729
  730. 730///|
  731. 731/// 更新概率模型(基于统计计数器,EMA 方式)
  732. 732fn vp8_enc_adaptive_probs_update(probs : Vp8EncAdaptiveProbs) -> Unit {
  733. 733 // 更新 token 概率
  734. 734○ for i in 0..<64 {
  735. 735○ let count = probs.token_counts[i]
  736. 736 if count > 0 {
  737. 737 // EMA 更新:new_prob = old_prob * 0.875 + observed * 0.125
  738. 738○ let observed = (255 * count / (count + 1)).clamp(min=1, max=254)
  739. 739 probs.token_probs[i] = (probs.token_probs[i] * 7 + observed) / 8
  740. 740 probs.token_counts[i] = 0
  741. 741 }
  742. 742 }
  743. 743 // 更新预测模式概率
  744. 744 let total = probs.pred_mode_counts[0] +
  745. 745 probs.pred_mode_counts[1] +
  746. 746 probs.pred_mode_counts[2] +
  747. 747 probs.pred_mode_counts[3]
  748. 748 if total > 0 {
  749. 749○ for i in 0..<4 {
  750. 750○ let observed = (255 * probs.pred_mode_counts[i] / total).clamp(
  751. 751 min=1,
  752. 752 max=254,
  753. 753 )
  754. 754 probs.pred_mode_probs[i] = (probs.pred_mode_probs[i] * 7 + observed) / 8
  755. 755 probs.pred_mode_counts[i] = 0
  756. 756 }
  757. 757 }
  758. 758 probs.blocks_since_update = 0
  759. 759}
  760. 760
  761. 761///|
  762. 762/// 记录 token 统计
  763. 763fn _vp8_enc_adaptive_probs_record_token(
  764. 764 probs : Vp8EncAdaptiveProbs,
  765. 765 pos : Int32,
  766. 766 token_type : Int32,
  767. 767) -> Unit {
  768. 768○ if pos >= 0 && pos < 16 && token_type >= 0 && token_type < 4 {
  769. 769○ probs.token_counts[pos * 4 + token_type] += 1
  770. 770 }
  771. 771}
  772. 772
  773. 773///|
  774. 774/// 记录预测模式统计
  775. 775fn vp8_enc_adaptive_probs_record_mode(
  776. 776 probs : Vp8EncAdaptiveProbs,
  777. 777 mode : Int32,
  778. 778) -> Unit {
  779. 779● if mode >= 0 && mode < 4 {
  780. 780● probs.pred_mode_counts[mode] += 1
  781. 781 }
  782. 782}
  783. 783
  784. 784// ==================== VP8 Frame Header ====================
  785. 785
  786. 786///|
  787. 787/// 构建 VP8 frame header (key frame)
  788. 788fn vp8_build_frame_header(
  789. 789 width : Int32,
  790. 790 height : Int32,
  791. 791 first_part_size : Int32,
  792. 792) -> Bytes {
  793. 793● let result : Array[Byte] = []
  794. 794 // 3 bytes: frame tag
  795. 795 let tag = (0 << 0) | (0 << 1) | (1 << 4) | (first_part_size << 5)
  796. 796● result.push((tag & 0xFF).to_byte())
  797. 797● result.push(((tag >> 8) & 0xFF).to_byte())
  798. 798● result.push(((tag >> 16) & 0xFF).to_byte())
  799. 799 // 3 bytes: start code
  800. 800● result.push(b'\x9D')
  801. 801● result.push(b'\x01')
  802. 802● result.push(b'\x2A')
  803. 803 // 2 bytes: width + horizontal scale
  804. 804● result.push((width & 0xFF).to_byte())
  805. 805● result.push(((width >> 8) & 0x3F).to_byte())
  806. 806 // 2 bytes: height + vertical scale
  807. 807● result.push((height & 0xFF).to_byte())
  808. 808● result.push(((height >> 8) & 0x3F).to_byte())
  809. 809● Bytes::from_array(result)
  810. 810}
  811. 811
  812. 812///|
  813. 813/// 构建 WebP RIFF 容器
  814. 814fn vp8_build_webp_container(
  815. 815 width : Int32,
  816. 816 height : Int32,
  817. 817 vp8_data : Bytes,
  818. 818) -> Bytes {
  819. 819● let result : Array[Byte] = []
  820. 820 // RIFF header
  821. 821● result.push(b'\x52') // R
  822. 822● result.push(b'\x49') // I
  823. 823● result.push(b'\x46') // F
  824. 824● result.push(b'\x46') // F
  825. 825 // file size (placeholder)
  826. 826● let file_size_pos = result.length()
  827. 827● result.push(b'\x00')
  828. 828● result.push(b'\x00')
  829. 829● result.push(b'\x00')
  830. 830● result.push(b'\x00')
  831. 831 // WEBP
  832. 832● result.push(b'\x57') // W
  833. 833● result.push(b'\x45') // E
  834. 834● result.push(b'\x42') // B
  835. 835● result.push(b'\x50') // P
  836. 836 // VP8 chunk
  837. 837● result.push(b'\x56') // V
  838. 838● result.push(b'\x50') // P
  839. 839● result.push(b'\x38') // 8
  840. 840● result.push(b'\x20') // space
  841. 841 // chunk size (placeholder)
  842. 842● let chunk_size_pos = result.length()
  843. 843● result.push(b'\x00')
  844. 844● result.push(b'\x00')
  845. 845● result.push(b'\x00')
  846. 846● result.push(b'\x00')
  847. 847 // VP8 data
  848. 848● let vp8_len = vp8_data.length()
  849. 849 for i in 0..<vp8_len {
  850. 850● result.push(vp8_data[i])
  851. 851 }
  852. 852 // 填充到偶数长度
  853. 853 if vp8_len % 2 != 0 {
  854. 854● result.push(b'\x00')
  855. 855 }
  856. 856 // 回填 chunk size
  857. 857 let chunk_size = vp8_len
  858. 858● result[chunk_size_pos] = (chunk_size & 0xFF).to_byte()
  859. 859● result[chunk_size_pos + 1] = ((chunk_size >> 8) & 0xFF).to_byte()
  860. 860● result[chunk_size_pos + 2] = ((chunk_size >> 16) & 0xFF).to_byte()
  861. 861● result[chunk_size_pos + 3] = ((chunk_size >> 24) & 0xFF).to_byte()
  862. 862 // 回填 file size
  863. 863● let total_size = result.length() - 8
  864. 864● result[file_size_pos] = (total_size & 0xFF).to_byte()
  865. 865● result[file_size_pos + 1] = ((total_size >> 8) & 0xFF).to_byte()
  866. 866● result[file_size_pos + 2] = ((total_size >> 16) & 0xFF).to_byte()
  867. 867● result[file_size_pos + 3] = ((total_size >> 24) & 0xFF).to_byte()
  868. 868 let _ = width
  869. 869 let _ = height
  870. 870● Bytes::from_array(result)
  871. 871}
  872. 872
  873. 873// ==================== Main Encoder ====================
  874. 874
  875. 875///|
  876. 876/// WebP lossy 编码(完整实现)
  877. 877/// 实现: VP8 key frame, I16x16 DC 预测, 4x4 DCT, 量化, 布尔算术编码
  878. 878/// quality: 1-100 (越高越好质量,文件越大)
  879. 879/// ⚠️ 实测(2026-11-25):产物同样不符合 VP8 规范(ffmpeg 报 `Invalid partitions`)。
  880. 880/// 合法 WebP 编码请用 [`encode_webp_lossless`]。
  881. 881#deprecated("产物不符合 VP8 规范,请改用 encode_webp_lossless", skip_current_package=true)
  882. 882pub fn encode_webp_lossy_full(
  883. 883 img : @types.Image,
  884. 884 quality~ : Int32 = 75,
  885. 885) -> Bytes raise @types.LoadError {
  886. 886 let w = img.width
  887. 887 let h = img.height
  888. 888 let ch = img.channels
  889. 889 if w <= 0 || h <= 0 {
  890. 890 raise @types.LoadError::EncodeFailed("WebP: 尺寸无效")
  891. 891 }
  892. 892 if ch != 3 && ch != 4 {
  893. 893 raise @types.LoadError::EncodeFailed("WebP: 仅支持 RGB/RGBA")
  894. 894 }
  895. 895
  896. 896 // 1. RGB → YUV420
  897. 897 let (y_plane, u_plane, v_plane) = rgb_to_yuv420(img)
  898. 898
  899. 899 // 2. 计算量化参数
  900. 900 let quant = vp8_calc_quant_params(quality)
  901. 901
  902. 902 // 3. 编码宏块
  903. 903 let mb_w = (w + 15) / 16
  904. 904 let mb_h = (h + 15) / 16
  905. 905 let enc = Vp8BoolEncoder::new()
  906. 906 // 自适应概率模型
  907. 907 let adaptive_probs = vp8_enc_adaptive_probs_new()
  908. 908 // Segment 参数(基于图像复杂度自动分配)
  909. 909 let segment = vp8_enc_segment_params_new(y_plane, w, h, quant.y_ac)
  910. 910 // 重建的 Y 平面(用于环路滤波和后续预测)
  911. 911 let recon_y : Array[Int32] = Array::make(w * h, 128)
  912. 912 for i in 0..<(w * h) {
  913. 913 recon_y[i] = y_plane[i]
  914. 914 }
  915. 915
  916. 916 for mb_y in 0..<mb_h {
  917. 917 for mb_x in 0..<mb_w {
  918. 918 // 选择最佳 I16x16 预测模式(基于 SAD 代价)
  919. 919 let pred_mode = vp8_select_i16x16_mode(recon_y, mb_x, mb_y, w, h)
  920. 920 // 编码预测模式(使用自适应概率)
  921. 921 let mode_idx = match pred_mode {
  922. 922 Vp8I16x16PredMode::I16x16DcPred => 0
  923. 923 Vp8I16x16PredMode::I16x16TrueMotionPred => 1
  924. 924 Vp8I16x16PredMode::I16x16HPred => 2
  925. 925 Vp8I16x16PredMode::I16x16VPred => 3
  926. 926 }
  927. 927 // 使用自适应概率编码预测模式(简化:固定概率编码,记录统计)
  928. 928 enc.encode_uint(mode_idx, 2)
  929. 929 vp8_enc_adaptive_probs_record_mode(adaptive_probs, mode_idx)
  930. 930
  931. 931 // 获取预测像素
  932. 932 let pred = vp8_get_i16x16_prediction(pred_mode, recon_y, mb_x, mb_y, w, h)
  933. 933
  934. 934 // 计算残差
  935. 935 let residual : Array[Int32] = Array::make(256, 0)
  936. 936 for y in 0..<16 {
  937. 937 for x in 0..<16 {
  938. 938 let px = mb_x * 16 + x
  939. 939 let py = mb_y * 16 + y
  940. 940 if px < w && py < h {
  941. 941 residual[y * 16 + x] = y_plane[py * w + px] - pred[y * 16 + x]
  942. 942 }
  943. 943 }
  944. 944 }
  945. 945
  946. 946 // 提取 16 个 4x4 子块的 DC 系数
  947. 947 let dc_block : Array[Int32] = Array::make(16, 0)
  948. 948 for sub_y in 0..<4 {
  949. 949 for sub_x in 0..<4 {
  950. 950 let mut sum = 0
  951. 951 for y in 0..<4 {
  952. 952 for x in 0..<4 {
  953. 953 sum += residual[(sub_y * 4 + y) * 16 + (sub_x * 4 + x)]
  954. 954 }
  955. 955 }
  956. 956 dc_block[sub_y * 4 + sub_x] = sum / 16
  957. 957 }
  958. 958 }
  959. 959
  960. 960 // 获取当前宏块的量化参数(考虑 segment)
  961. 961 let mb_quant = vp8_enc_get_mb_quant(segment, mb_x, mb_y, mb_w, quant.y_ac)
  962. 962
  963. 963 // WHT 变换 DC 系数
  964. 964 let dc_transformed = vp8_fwht_4x4(dc_block)
  965. 965 let dc_quantized = vp8_quantize_4x4(dc_transformed, mb_quant * 2)
  966. 966
  967. 967 // 编码 DC 系数
  968. 968 vp8_encode_block_tokens(enc, dc_quantized, true)
  969. 969
  970. 970 // 对每个 4x4 子块进行 DCT 和编码 AC 系数
  971. 971 for sub_y in 0..<4 {
  972. 972 for sub_x in 0..<4 {
  973. 973 // 提取 4x4 子块
  974. 974 let block : Array[Int32] = Array::make(16, 0)
  975. 975 for y in 0..<4 {
  976. 976 for x in 0..<4 {
  977. 977 block[y * 4 + x] = residual[(sub_y * 4 + y) * 16 + (sub_x * 4 + x)]
  978. 978 }
  979. 979 }
  980. 980 // DCT 变换
  981. 981 let transformed = vp8_fdct_4x4(block)
  982. 982 // DC 系数已经在 WHT 中处理,这里置 0
  983. 983 transformed[0] = 0
  984. 984 // 量化(使用 segment 调整后的量化参数)
  985. 985 let quantized = vp8_quantize_4x4(transformed, mb_quant)
  986. 986 // 编码
  987. 987 vp8_encode_block_tokens(enc, quantized, false)
  988. 988 }
  989. 989 }
  990. 990 // 更新自适应概率模型(每 8 个宏块更新一次)
  991. 991 adaptive_probs.blocks_since_update += 1
  992. 992 if adaptive_probs.blocks_since_update >= adaptive_probs.update_interval {
  993. 993 vp8_enc_adaptive_probs_update(adaptive_probs)
  994. 994 }
  995. 995 }
  996. 996 }
  997. 997
  998. 998 // 3.5 环路滤波(对重建的 Y 平面进行宏块边界滤波)
  999. 999 let filter_level = (quant.y_ac / 4).clamp(min=0, max=63)
  1000. 1000 vp8_encoder_loop_filter(recon_y, w, h, filter_level)
  1001. 1001
  1002. 1002 // 4. 完成编码
  1003. 1003 let token_data = enc.finish()
  1004. 1004
  1005. 1005 // 5. 构建 VP8 frame header
  1006. 1006 let header = vp8_build_frame_header(w, h, token_data.length())
  1007. 1007
  1008. 1008 // 6. 合并 VP8 数据
  1009. 1009 let vp8_data : Array[Byte] = []
  1010. 1010 for i in 0..<header.length() {
  1011. 1011 vp8_data.push(header[i])
  1012. 1012 }
  1013. 1013 for i in 0..<token_data.length() {
  1014. 1014 vp8_data.push(token_data[i])
  1015. 1015 }
  1016. 1016
  1017. 1017 // 7. 构建 WebP 容器
  1018. 1018 let result = vp8_build_webp_container(w, h, Bytes::from_array(vp8_data))
  1019. 1019
  1020. 1020 let _ = u_plane
  1021. 1021 let _ = v_plane
  1022. 1022 result
  1023. 1023}