image.codec\codec\webp_encode.mbt
100% · 83 / 83 points · 235 linesBackground color reports the state of each line. Underlined characters mark exact instrumented byte offsets; hover them to inspect the visit count.
- 1
///| - 2
/// # WebP 编码 WebP Encode - 3
/// - 4
/// WebP 图像格式编码 - 5
/// WebP 图像格式编码 WebP image format encoding - 6
// 纯 MoonBit WebP lossy 编码器 (VP8) - 7
// 规范: https://datatracker.ietf.org/doc/html/rfc6386 - 8
// 实现: 仅 intra 帧 (key frame), DC-only 预测, 固定量化 - 9
// 产出: 可被标准 WebP 解码器解码的有效 VP8 bitstream - 10
- 11
///| - 12
/// VP8 Bool 编码器(算术编码) - 13
priv struct BoolEncoder { - 14
output : Array[Byte] - 15
mut low : Int32 - 16
mut count : Int32 - 17
mut range : Int32 - 18
} - 19
- 20
///| - 21
fn BoolEncoder::new() -> BoolEncoder { - 22●
{ output: [], low: 0, count: 0, range: 255, } - 23
} - 24
- 25
///| - 26
/// 编码一个 bool 值,probability 为 0 时编码 0 - 27
fn BoolEncoder::encode_bool( - 28
self : BoolEncoder, - 29
bit : Int32, - 30
probability : Int32, - 31
) -> Unit { - 32●
let split = 1 + (((self.range - 1) * probability) >> 8) - 33
if bit != 0 { - 34●
self.low += split - 35
self.range -= split - 36
} else { - 37●
self.range = split - 38
} - 39
while self.range < 128 { - 40●
self.shift() - 41
self.range = self.range << 1 - 42
} - 43
} - 44
- 45
///| - 46
fn BoolEncoder::shift(self : BoolEncoder) -> Unit { - 47●
let bit = if ((self.low >> 8) & 1) != 0 { 1 } else { 0 } - 48
self.low = (self.low << 1) & 0xFFFF - 49
self.count += 1 - 50
if self.count == 8 { - 51●
self.output.push(bit.to_byte()) - 52
self.count = 0 - 53
} - 54
} - 55
- 56
///| - 57
/// 编码固定概率的 bool (50%) - 58
fn BoolEncoder::encode_bit(self : BoolEncoder, bit : Int32) -> Unit { - 59●
self.encode_bool(bit, 128) - 60
} - 61
- 62
///| - 63
/// 编码无符号整数 (n bits, MSB first) - 64
fn BoolEncoder::encode_uint( - 65
self : BoolEncoder, - 66
value : Int32, - 67
n : Int32, - 68
) -> Unit { - 69●
for i in 0..<n { - 70●
let bit = (value >> (n - 1 - i)) & 1 - 71●
self.encode_bit(bit) - 72
} - 73
} - 74
- 75
///| - 76
/// 编码带符号整数 - 77
fn BoolEncoder::encode_int( - 78
self : BoolEncoder, - 79
value : Int32, - 80
n : Int32, - 81
) -> Unit { - 82●
if value < 0 { - 83●
self.encode_bit(1) - 84●
self.encode_uint(-value, n) - 85
} else { - 86●
self.encode_bit(0) - 87●
self.encode_uint(value, n) - 88
} - 89
} - 90
- 91
///| - 92
/// 完成编码,刷新剩余 bits - 93
fn BoolEncoder::finish(self : BoolEncoder) -> Bytes { - 94●
for _ in 0..<self.count { - 95●
self.output.push(0) - 96
} - 97●
Bytes::from_array(self.output) - 98
} - 99
- 100
///| - 101
/// 构建 WebP RIFF 容器 - 102
fn build_webp_container( - 103
width : Int32, - 104
height : Int32, - 105
vp8_data : Bytes, - 106
) -> Bytes { - 107●
let result : Array[Byte] = [] - 108●
result.push(b'\x52') - 109●
result.push(b'\x49') - 110●
result.push(b'\x46') - 111●
result.push(b'\x46') - 112●
let file_size_pos = result.length() - 113●
result.push(b'\x00') - 114●
result.push(b'\x00') - 115●
result.push(b'\x00') - 116●
result.push(b'\x00') - 117●
result.push(b'\x57') - 118●
result.push(b'\x45') - 119●
result.push(b'\x42') - 120●
result.push(b'\x50') - 121●
result.push(b'\x56') - 122●
result.push(b'\x50') - 123●
result.push(b'\x38') - 124●
result.push(b'\x20') - 125●
let chunk_size_pos = result.length() - 126●
result.push(b'\x00') - 127●
result.push(b'\x00') - 128●
result.push(b'\x00') - 129●
result.push(b'\x00') - 130●
let vp8_len = vp8_data.length() - 131
for i in 0..<vp8_len { - 132●
result.push(vp8_data[i]) - 133
} - 134
let chunk_size = vp8_len - 135●
result[chunk_size_pos] = (chunk_size & 0xFF).to_byte() - 136●
result[chunk_size_pos + 1] = ((chunk_size >> 8) & 0xFF).to_byte() - 137●
result[chunk_size_pos + 2] = ((chunk_size >> 16) & 0xFF).to_byte() - 138●
result[chunk_size_pos + 3] = ((chunk_size >> 24) & 0xFF).to_byte() - 139●
let total_size = result.length() - 8 - 140●
result[file_size_pos] = (total_size & 0xFF).to_byte() - 141●
result[file_size_pos + 1] = ((total_size >> 8) & 0xFF).to_byte() - 142●
result[file_size_pos + 2] = ((total_size >> 16) & 0xFF).to_byte() - 143●
result[file_size_pos + 3] = ((total_size >> 24) & 0xFF).to_byte() - 144
let _ = width - 145
let _ = height - 146●
Bytes::from_array(result) - 147
} - 148
- 149
///| - 150
/// 构建 VP8 frame header (key frame) - 151
fn build_vp8_frame_header( - 152
width : Int32, - 153
height : Int32, - 154
first_part_size : Int32, - 155
) -> Bytes { - 156●
let result : Array[Byte] = [] - 157
let tag = (0 << 0) | (0 << 1) | (1 << 4) | (first_part_size << 5) - 158●
result.push((tag & 0xFF).to_byte()) - 159●
result.push(((tag >> 8) & 0xFF).to_byte()) - 160●
result.push(((tag >> 16) & 0xFF).to_byte()) - 161●
result.push(b'\x9D') - 162●
result.push(b'\x01') - 163●
result.push(b'\x2A') - 164●
result.push((width & 0xFF).to_byte()) - 165●
result.push(((width >> 8) & 0xFF).to_byte()) - 166●
result.push((height & 0xFF).to_byte()) - 167●
result.push(((height >> 8) & 0xFF).to_byte()) - 168●
Bytes::from_array(result) - 169
} - 170
- 171
///| - 172
/// WebP lossy 编码(纯 MoonBit,全目标可用) - 173
/// 实现: VP8 key frame, DC-only 预测, 固定量化 - 174
/// quality: 1-100 (越高越好质量,文件越大) - 175
/// ⚠️ 实测(2026-11-25):产物**不符合 VP8 规范**。RIFF 容器正确,但缺少 first partition - 176
/// 中的分段/滤波/量化/概率更新与 token partition 尺寸表,first_part_size 被写成整个 - 177
/// token 流长度。ffmpeg 报 `Invalid partitions`,浏览器同样无法解码。 - 178
/// 本函数仅为占位实现,不得在任何能力宣称中使用;合法 VP8/VP8L 编码器列为后续工作。 - 179
/// 本库解码器仅支持 lossless (VP8L),也无法解此函数的输出。 - 180
/// 自 S02 M3 起改用 [`encode_webp_lossless`](VP8L,产物经 ffmpeg / libwebp 逐字节校验)。 - 181
#deprecated("产物不符合 VP8 规范,请改用 encode_webp_lossless") - 182
pub fn encode_webp_lossy_pure( - 183
img : @types.Image, - 184
quality~ : Int32 = 75, - 185
) -> Bytes raise @types.LoadError { - 186
let w = img.width - 187
let h = img.height - 188
let ch = img.channels - 189
if w <= 0 || h <= 0 { - 190
raise @types.LoadError::EncodeFailed("WebP: 尺寸无效") - 191
} - 192
if ch != 3 && ch != 4 { - 193
raise @types.LoadError::EncodeFailed("WebP: 仅支持 RGB/RGBA") - 194
} - 195
let q_factor = ((100 - quality).clamp(min=1, max=99) * 63 / 100).clamp( - 196
min=1, - 197
max=63, - 198
) - 199
// 转为 Y 分量 - 200
let y_data : Array[Int32] = Array::make(w * h, 0) - 201
for y in 0..<h { - 202
for x in 0..<w { - 203
let idx = (y * w + x) * ch - 204
let r = img.data[idx].to_int() - 205
let g = img.data[idx + 1].to_int() - 206
let b = img.data[idx + 2].to_int() - 207
y_data[y * w + x] = (r * 66 + g * 129 + b * 25 + 128) >> 8 - 208
} - 209
} - 210
let mb_w = (w + 15) / 16 - 211
let mb_h = (h + 15) / 16 - 212
let enc = BoolEncoder::new() - 213
for mby in 0..<mb_h { - 214
for mbx in 0..<mb_w { - 215
// DC 值: 取 16x16 块中心像素 - 216
let cx = (mbx * 16 + 8).clamp(min=0, max=w - 1) - 217
let cy = (mby * 16 + 8).clamp(min=0, max=h - 1) - 218
let dc_val = y_data[cy * w + cx] - 219
let quantized_dc = (dc_val - 128 + q_factor / 2) / q_factor - 220
enc.encode_int(quantized_dc, 7) - 221
} - 222
} - 223
let token_data = enc.finish() - 224
let header = build_vp8_frame_header(w, h, token_data.length()) - 225
let vp8_data : Array[Byte] = [] - 226
for i in 0..<header.length() { - 227
vp8_data.push(header[i]) - 228
} - 229
for i in 0..<token_data.length() { - 230
vp8_data.push(token_data[i]) - 231
} - 232
let result = build_webp_container(w, h, Bytes::from_array(vp8_data)) - 233
let _ = q_factor - 234
result - 235
}