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