image.codec\codec\webp_encode.mbt

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