image.codec\codec\jpeg_progressive_script.mbt

95.9% · 283 / 295 points · 747 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/// # progressive JPEG · 扫描脚本可配置(`encode_jpeg_progressive_420_scripted`)
  3. 3///
  4. 4/// 把"固定 8 条扫描"升级成**按脚本驱动**:每条扫描给出分量集、`Ss/Se`(spectral selection)
  5. 5/// 与 `Ah/Al`(successive approximation),逐条写自己的 DHT + SOS。
  6. 6///
  7. 7/// 默认脚本 `jpeg_progressive_script_libjpeg()` 复刻 libjpeg `jpeg_simple_progression()`
  8. 8/// 对 YCbCr 的 10 条扫描:DC 首扫 → Y `1–5`(Al=2) → Cr/Cb 全带(Al=1) → Y `6–63`(Al=2) →
  9. 9/// DC 细化 → Y 全带 `Ah=2 Al=1` → Cr/Cb 全带细化 → Y 全带细化(亮度最低位最后发)。
  10. 10///
  11. 11/// 与 4:2:0 固定 8 扫描版共用同一套系数平面(Y `stride_y`、Cb/Cr `stride_c`)与
  12. 12/// `prog420_pixel_ycbcr` / `jpeg_progressive_quantize_block`;差别只在扫描的组织方式,
  13. 13/// 顺带把 AC 表改成**逐扫描按频次重建**(libjpeg `optimize_coding` 同口径)。
  14. 14
  15. 15///|
  16. 16/// 一条 progressive 扫描(字段与 libjpeg `jpeg_scan_info` 对齐)。
  17. 17/// `comps` 用本库的分量序号:0 = Y、1 = Cb、2 = Cr。
  18. 18pub(all) struct JpegProgScan {
  19. 19 comps : Array[Int32]
  20. 20 ss : Int32
  21. 21 se : Int32
  22. 22 ah : Int32
  23. 23 al : Int32
  24. 24}
  25. 25
  26. 26///|
  27. 27/// libjpeg `jpeg_simple_progression()` 的 YCbCr 默认 10 条扫描。
  28. 28pub fn jpeg_progressive_script_libjpeg() -> Array[JpegProgScan] {
  29. 29● [
  30. 30 JpegProgScan::{ comps: [0, 1, 2], ss: 0, se: 0, ah: 0, al: 1, },
  31. 31 JpegProgScan::{ comps: [0], ss: 1, se: 5, ah: 0, al: 2, },
  32. 32 JpegProgScan::{ comps: [2], ss: 1, se: 63, ah: 0, al: 1, },
  33. 33 JpegProgScan::{ comps: [1], ss: 1, se: 63, ah: 0, al: 1, },
  34. 34 JpegProgScan::{ comps: [0], ss: 6, se: 63, ah: 0, al: 2, },
  35. 35 JpegProgScan::{ comps: [0, 1, 2], ss: 0, se: 0, ah: 1, al: 0, },
  36. 36 JpegProgScan::{ comps: [0], ss: 1, se: 63, ah: 2, al: 1, },
  37. 37 JpegProgScan::{ comps: [2], ss: 1, se: 63, ah: 1, al: 0, },
  38. 38 JpegProgScan::{ comps: [1], ss: 1, se: 63, ah: 1, al: 0, },
  39. 39 JpegProgScan::{ comps: [0], ss: 1, se: 63, ah: 1, al: 0, },
  40. 40 ]
  41. 41}
  42. 42
  43. 43///|
  44. 44/// 0.1.30 固定 8 条扫描等价脚本(DC 首扫 Al=1 → 3×AC 首扫 Al=1 → DC 细化 → 3×AC 细化)。
  45. 45pub fn jpeg_progressive_script_eight() -> Array[JpegProgScan] {
  46. 46● [
  47. 47 JpegProgScan::{ comps: [0, 1, 2], ss: 0, se: 0, ah: 0, al: 1, },
  48. 48 JpegProgScan::{ comps: [0], ss: 1, se: 63, ah: 0, al: 1, },
  49. 49 JpegProgScan::{ comps: [1], ss: 1, se: 63, ah: 0, al: 1, },
  50. 50 JpegProgScan::{ comps: [2], ss: 1, se: 63, ah: 0, al: 1, },
  51. 51 JpegProgScan::{ comps: [0, 1, 2], ss: 0, se: 0, ah: 1, al: 0, },
  52. 52 JpegProgScan::{ comps: [0], ss: 1, se: 63, ah: 1, al: 0, },
  53. 53 JpegProgScan::{ comps: [2], ss: 1, se: 63, ah: 1, al: 0, },
  54. 54 JpegProgScan::{ comps: [1], ss: 1, se: 63, ah: 1, al: 0, },
  55. 55 ]
  56. 56}
  57. 57
  58. 58///|
  59. 59/// 发挂起的 EOBRUN(不带修正位缓冲;AC 首扫用)。
  60. 60fn prog_emit_eobrun(
  61. 61 w : JpegBitWriter,
  62. 62 enc : JpegHuffmanEncoder,
  63. 63 freq : Array[Int32],
  64. 64 eobrun : Int32,
  65. 65) -> Unit {
  66. 66● if eobrun > 0 {
  67. 67● let nbits = jpeg_category(eobrun) - 1
  68. 68● jpeg_prog_emit_sym(w, enc, freq, nbits << 4)
  69. 69 if nbits > 0 {
  70. 70● jpeg_prog_emit_value(w, freq, eobrun - (1 << nbits), nbits)
  71. 71 }
  72. 72 }
  73. 73}
  74. 74
  75. 75///|
  76. 76/// 一条 AC 首扫(单分量平面,band `Ss..Se`,点变换 `Al`)。`freq` 非空时只计频。
  77. 77fn prog_ac_first_scan(
  78. 78 w : JpegBitWriter,
  79. 79 enc : JpegHuffmanEncoder,
  80. 80 freq : Array[Int32],
  81. 81 plane : Array[Int32],
  82. 82 stride : Int32,
  83. 83 bx_max : Int32,
  84. 84 by_max : Int32,
  85. 85 ss : Int32,
  86. 86 se : Int32,
  87. 87 al : Int32,
  88. 88) -> Unit {
  89. 89● let mut eobrun = 0
  90. 90 for by in 0..<by_max {
  91. 91● for bx in 0..<bx_max {
  92. 92● let base = (by * stride + bx) * 64
  93. 93 let mut has_nz = false
  94. 94 let mut k = ss
  95. 95 while k <= se {
  96. 96● if jpeg_prog_shift(plane[base + k], al) != 0 {
  97. 97● has_nz = true
  98. 98 k = se
  99. 99 }
  100. 100 k = k + 1
  101. 101 }
  102. 102 if !has_nz {
  103. 103● eobrun += 1
  104. 104 if eobrun == PROGRESSIVE_MAX_EOBRUN {
  105. 105○ prog_emit_eobrun(w, enc, freq, eobrun)
  106. 106 eobrun = 0
  107. 107 }
  108. 108 continue
  109. 109 }
  110. 110 if eobrun > 0 {
  111. 111● prog_emit_eobrun(w, enc, freq, eobrun)
  112. 112 eobrun = 0
  113. 113 }
  114. 114 let mut run = 0
  115. 115 k = ss
  116. 116 while k <= se {
  117. 117● let c = jpeg_prog_shift(plane[base + k], al)
  118. 118 if c == 0 {
  119. 119● run += 1
  120. 120 } else {
  121. 121● while run > 15 {
  122. 122● jpeg_prog_emit_sym(w, enc, freq, 0xF0)
  123. 123 run -= 16
  124. 124 }
  125. 125● let size = jpeg_category(c)
  126. 126● jpeg_prog_emit_sym(w, enc, freq, (run << 4) | size)
  127. 127● jpeg_prog_emit_value(w, freq, c, size)
  128. 128 run = 0
  129. 129 }
  130. 130 k = k + 1
  131. 131 }
  132. 132 if run > 0 {
  133. 133 // 块尾残余零:立即 EOB 收尾(不进 EOBRUN),与 0.1.30 固定脚本同口径
  134. 134● jpeg_prog_emit_sym(w, enc, freq, 0)
  135. 135 }
  136. 136 }
  137. 137 }
  138. 138 if eobrun > 0 {
  139. 139● prog_emit_eobrun(w, enc, freq, eobrun)
  140. 140 }
  141. 141}
  142. 142
  143. 143///|
  144. 144/// 一条 AC 细化扫描(单分量平面,band `Ss..Se`,`Ah>0`,点变换 `Al`)。
  145. 145/// 新非零判据是 `|c|>>Al == 1`(libjpeg `encode_mcu_AC_refine` 的 `temp == 1`),
  146. 146/// `|c|>>Al > 1` 的系数是"更高位已发过",只补一位修正位;修正位取 `|c|>>Al` 的最低位。
  147. 147fn prog_ac_refine_scan(
  148. 148 w : JpegBitWriter,
  149. 149 enc : JpegHuffmanEncoder,
  150. 150 freq : Array[Int32],
  151. 151 plane : Array[Int32],
  152. 152 stride : Int32,
  153. 153 bx_max : Int32,
  154. 154 by_max : Int32,
  155. 155 ss : Int32,
  156. 156 se : Int32,
  157. 157 al : Int32,
  158. 158) -> Unit {
  159. 159● let absv = Array::make(64, 0)
  160. 160 let be : Array[Int32] = []
  161. 161 let br : Array[Int32] = []
  162. 162 let mut eobrun = 0
  163. 163 for by in 0..<by_max {
  164. 164● for bx in 0..<bx_max {
  165. 165● let base = (by * stride + bx) * 64
  166. 166 let mut has_nz = false
  167. 167 let mut eob = ss - 1
  168. 168 let mut k = ss
  169. 169 while k <= se {
  170. 170● let c = plane[base + k]
  171. 171● let a = if c < 0 { -c } else { c }
  172. 172 let av = a >> al
  173. 173 absv[k] = av
  174. 174 if av != 0 {
  175. 175● has_nz = true
  176. 176 }
  177. 177 if av == 1 {
  178. 178● eob = k
  179. 179 }
  180. 180 k = k + 1
  181. 181 }
  182. 182 if has_nz && eobrun > 0 {
  183. 183● jpeg_prog_flush_eobrun(w, enc, freq, eobrun, be)
  184. 184 eobrun = 0
  185. 185 }
  186. 186 let mut r = 0
  187. 187 k = ss
  188. 188 while k <= se {
  189. 189● let av = absv[k]
  190. 190 if av == 0 {
  191. 191● r += 1
  192. 192 k = k + 1
  193. 193 continue
  194. 194 }
  195. 195 while r > 15 && k <= eob {
  196. 196● jpeg_prog_flush_eobrun(w, enc, freq, eobrun, be)
  197. 197 eobrun = 0
  198. 198● jpeg_prog_emit_sym(w, enc, freq, 0xF0)
  199. 199 r -= 16
  200. 200● jpeg_prog_flush_corr(w, freq, br)
  201. 201 }
  202. 202 if av > 1 {
  203. 203● br.push(av & 1)
  204. 204 } else {
  205. 205● jpeg_prog_flush_eobrun(w, enc, freq, eobrun, be)
  206. 206 eobrun = 0
  207. 207● jpeg_prog_emit_sym(w, enc, freq, (r << 4) | 1)
  208. 208● jpeg_prog_emit_bit(w, freq, if plane[base + k] < 0 { 0 } else { 1 })
  209. 209● jpeg_prog_flush_corr(w, freq, br)
  210. 210 r = 0
  211. 211 }
  212. 212 k = k + 1
  213. 213 }
  214. 214● if r > 0 || br.length() > 0 {
  215. 215● eobrun += 1
  216. 216 for b in br {
  217. 217● be.push(b)
  218. 218 }
  219. 219● br.clear()
  220. 220 if eobrun == PROGRESSIVE_MAX_EOBRUN {
  221. 221○ jpeg_prog_flush_eobrun(w, enc, freq, eobrun, be)
  222. 222 eobrun = 0
  223. 223 }
  224. 224 }
  225. 225 }
  226. 226 }
  227. 227○ if eobrun > 0 || be.length() > 0 {
  228. 228● jpeg_prog_flush_eobrun(w, enc, freq, eobrun, be)
  229. 229 }
  230. 230● jpeg_prog_flush_corr(w, freq, br)
  231. 231}
  232. 232
  233. 233///|
  234. 234/// 一条交错 DC 首扫(4:2:0 的 MCU 顺序:4 个 Y 块 + Cb + Cr)。
  235. 235fn prog420_dc_first(
  236. 236 w : JpegBitWriter,
  237. 237 enc_lum : JpegHuffmanEncoder,
  238. 238 enc_chr : JpegHuffmanEncoder,
  239. 239 coefs_y : Array[Int32],
  240. 240 coefs_cb : Array[Int32],
  241. 241 coefs_cr : Array[Int32],
  242. 242 stride_y : Int32,
  243. 243 stride_c : Int32,
  244. 244 mcus_x : Int32,
  245. 245 mcus_y : Int32,
  246. 246 al : Int32,
  247. 247) -> Unit {
  248. 248● let prev : Array[Ref[Int32]] = [Ref(0), Ref(0), Ref(0)]
  249. 249 for my in 0..<mcus_y {
  250. 250● for mx in 0..<mcus_x {
  251. 251● for bi in 0..<4 {
  252. 252● let gx = mx * 2 + bi % 2
  253. 253 let gy = my * 2 + bi / 2
  254. 254 let dc = coefs_y[(gy * stride_y + gx) * 64] >> al
  255. 255 let diff = dc - prev[0].val
  256. 256 prev[0].val = dc
  257. 257● let cat = jpeg_category(diff)
  258. 258● jpeg_write_bits(w, enc_lum.codes[cat], enc_lum.lengths[cat])
  259. 259 if cat > 0 {
  260. 260● jpeg_write_bits(w, jpeg_value_bits(diff, cat), cat)
  261. 261 }
  262. 262 }
  263. 263 let cbase = (my * stride_c + mx) * 64
  264. 264 let dc_cb = coefs_cb[cbase] >> al
  265. 265 let diff_cb = dc_cb - prev[1].val
  266. 266 prev[1].val = dc_cb
  267. 267● let cat_cb = jpeg_category(diff_cb)
  268. 268● jpeg_write_bits(w, enc_chr.codes[cat_cb], enc_chr.lengths[cat_cb])
  269. 269 if cat_cb > 0 {
  270. 270● jpeg_write_bits(w, jpeg_value_bits(diff_cb, cat_cb), cat_cb)
  271. 271 }
  272. 272 let dc_cr = coefs_cr[cbase] >> al
  273. 273 let diff_cr = dc_cr - prev[2].val
  274. 274 prev[2].val = dc_cr
  275. 275● let cat_cr = jpeg_category(diff_cr)
  276. 276● jpeg_write_bits(w, enc_chr.codes[cat_cr], enc_chr.lengths[cat_cr])
  277. 277 if cat_cr > 0 {
  278. 278● jpeg_write_bits(w, jpeg_value_bits(diff_cr, cat_cr), cat_cr)
  279. 279 }
  280. 280 }
  281. 281 }
  282. 282}
  283. 283
  284. 284///|
  285. 285/// 一条交错 DC 细化扫描:每块只发 `(DC >> Al) & 1`。
  286. 286fn prog420_dc_refine(
  287. 287 w : JpegBitWriter,
  288. 288 coefs_y : Array[Int32],
  289. 289 coefs_cb : Array[Int32],
  290. 290 coefs_cr : Array[Int32],
  291. 291 stride_y : Int32,
  292. 292 stride_c : Int32,
  293. 293 mcus_x : Int32,
  294. 294 mcus_y : Int32,
  295. 295 al : Int32,
  296. 296) -> Unit {
  297. 297● for my in 0..<mcus_y {
  298. 298● for mx in 0..<mcus_x {
  299. 299● for bi in 0..<4 {
  300. 300● let gx = mx * 2 + bi % 2
  301. 301 let gy = my * 2 + bi / 2
  302. 302● jpeg_write_bits(w, (coefs_y[(gy * stride_y + gx) * 64] >> al) & 1, 1)
  303. 303 }
  304. 304 let cbase = (my * stride_c + mx) * 64
  305. 305● jpeg_write_bits(w, (coefs_cb[cbase] >> al) & 1, 1)
  306. 306● jpeg_write_bits(w, (coefs_cr[cbase] >> al) & 1, 1)
  307. 307 }
  308. 308 }
  309. 309}
  310. 310
  311. 311///|
  312. 312/// 校验脚本合法性(照 ITU-T T.81 对 progressive 参数的约束 + 本库 3 分量布局)。
  313. 313fn prog_script_check(
  314. 314 script : Array[JpegProgScan],
  315. 315) -> Unit raise @types.LoadError {
  316. 316● if script.length() == 0 {
  317. 317○ raise @types.LoadError::EncodeFailed("progressive 扫描脚本为空")
  318. 318 }
  319. 319 for s in script {
  320. 320● if s.ss < 0 || s.se > 63 || s.ss > s.se {
  321. 321○ raise @types.LoadError::EncodeFailed(
  322. 322 "progressive 扫描脚本 Ss/Se 越界",
  323. 323 )
  324. 324 }
  325. 325 if s.ah < 0 || s.ah > 13 || s.al < 0 || s.al > 13 {
  326. 326○ raise @types.LoadError::EncodeFailed(
  327. 327 "progressive 扫描脚本 Ah/Al 越界",
  328. 328 )
  329. 329 }
  330. 330● if s.comps.length() == 0 || s.comps.length() > 3 {
  331. 331○ raise @types.LoadError::EncodeFailed(
  332. 332 "progressive 扫描脚本分量数无效",
  333. 333 )
  334. 334 }
  335. 335● if s.ss != 0 && s.comps.length() != 1 {
  336. 336○ raise @types.LoadError::EncodeFailed(
  337. 337 "progressive 的 AC 扫描只能是单分量",
  338. 338 )
  339. 339 }
  340. 340 if s.ss == 0 && s.se != 0 {
  341. 341○ raise @types.LoadError::EncodeFailed(
  342. 342 "progressive 的 DC 扫描必须 Ss=Se=0",
  343. 343 )
  344. 344 }
  345. 345 for ci in s.comps {
  346. 346● if ci < 0 || ci > 2 {
  347. 347○ raise @types.LoadError::EncodeFailed(
  348. 348 "progressive 扫描脚本分量序号越界(仅 0/1/2)",
  349. 349 )
  350. 350 }
  351. 351 }
  352. 352 }
  353. 353}
  354. 354
  355. 355///|
  356. 356/// 4:2:0 渐进式编码 · 扫描脚本可配置。
  357. 357///
  358. 358/// 参数 Parameters:
  359. 359/// - `img` - 输入图像(1 或 3 通道)
  360. 360/// - `quality` - 质量 1–100
  361. 361/// - `script` - 扫描脚本(`jpeg_progressive_script_libjpeg()` 为 libjpeg 默认 10 段)
  362. 362///
  363. 363/// 返回 Return:
  364. 364/// - progressive JPEG(SOF2,Y `2×2`、Cb/Cr `1×1`)字节流
  365. 365///
  366. 366/// 错误 Errors:
  367. 367/// - `LoadError::EncodeFailed` - 尺寸无效、像素数超上限、脚本非法
  368. 368pub fn encode_jpeg_progressive_420_scripted(
  369. 369 img : @types.Image,
  370. 370 quality : Int32,
  371. 371 script : Array[JpegProgScan],
  372. 372) -> Bytes raise @types.LoadError {
  373. 373● let width = img.width
  374. 374 let height = img.height
  375. 375 if width <= 0 || height <= 0 {
  376. 376○ raise @types.LoadError::EncodeFailed("JPEG 尺寸无效")
  377. 377 }
  378. 378 if height > PROGRESSIVE_MAX_PIXELS / width {
  379. 379○ raise @types.LoadError::EncodeFailed(
  380. 380 "progressive 编码暂支持 ≤ 2,000,000 像素(量化系数缓存上限)",
  381. 381 )
  382. 382 }
  383. 383● prog_script_check(script)
  384. 384 let channels = img.channels
  385. 385 let data = img.data
  386. 386● let zz = jpeg_zigzag()
  387. 387● let quant_lum = jpeg_scaled_quant(std_quant_luminance(), quality)
  388. 388● let quant_chr = jpeg_scaled_quant(std_quant_chrominance(), quality)
  389. 389● let dc_lum_enc = build_huffman_encoder(std_dc_lum_bits(), std_dc_lum_vals())
  390. 390● let dc_chr_enc = build_huffman_encoder(std_dc_chr_bits(), std_dc_chr_vals())
  391. 391 let mcus_x = (width + 15) / 16
  392. 392 let mcus_y = (height + 15) / 16
  393. 393 let stride_y = mcus_x * 2
  394. 394 let stride_c = mcus_x
  395. 395 let y_fx = (width + 7) / 8
  396. 396 let y_fy = (height + 7) / 8
  397. 397 let c_fx = (width + 15) / 16
  398. 398 let c_fy = (height + 15) / 16
  399. 399● let coefs_y : Array[Int32] = Array::make(stride_y * (mcus_y * 2) * 64, 0)
  400. 400● let coefs_cb : Array[Int32] = Array::make(stride_c * c_fy * 64, 0)
  401. 401● let coefs_cr : Array[Int32] = Array::make(stride_c * c_fy * 64, 0)
  402. 402● let inv_lum : Array[Float] = Array::make(64, 0.0F)
  403. 403● let inv_chr : Array[Float] = Array::make(64, 0.0F)
  404. 404 for i in 0..<64 {
  405. 405● inv_lum[i] = 1.0F / (Float::from_int(quant_lum[i]) * 8.0F)
  406. 406● inv_chr[i] = 1.0F / (Float::from_int(quant_chr[i]) * 8.0F)
  407. 407 }
  408. 408● let tmp_i : Array[Int32] = Array::make(64, 0)
  409. 409● let shifted : Array[Int32] = Array::make(64, 0)
  410. 410● let dct_out : Array[Int32] = Array::make(64, 0)
  411. 411● let block : Array[Int32] = Array::make(64, 128)
  412. 412● let block_cr : Array[Int32] = Array::make(64, 128)
  413. 413 for by in 0..<(mcus_y * 2) {
  414. 414● for bx in 0..<stride_y {
  415. 415● for py in 0..<8 {
  416. 416● for px in 0..<8 {
  417. 417● let (yv, _, _) = prog420_pixel_ycbcr(
  418. 418 data,
  419. 419 channels,
  420. 420 width,
  421. 421 height,
  422. 422 bx * 8 + px,
  423. 423 by * 8 + py,
  424. 424 )
  425. 425 block[py * 8 + px] = yv
  426. 426 }
  427. 427 }
  428. 428● jpeg_progressive_quantize_block(
  429. 429 block,
  430. 430 inv_lum,
  431. 431 zz,
  432. 432 tmp_i,
  433. 433 shifted,
  434. 434 dct_out,
  435. 435 coefs_y,
  436. 436 (by * stride_y + bx) * 64,
  437. 437 )
  438. 438 }
  439. 439 }
  440. 440 for by in 0..<c_fy {
  441. 441● for bx in 0..<c_fx {
  442. 442● for py in 0..<8 {
  443. 443● for px in 0..<8 {
  444. 444● let sx = bx * 16 + px * 2
  445. 445 let sy = by * 16 + py * 2
  446. 446● let (_, cb0, cr0) = prog420_pixel_ycbcr(
  447. 447 data, channels, width, height, sx, sy,
  448. 448 )
  449. 449● let (_, cb1, cr1) = prog420_pixel_ycbcr(
  450. 450 data,
  451. 451 channels,
  452. 452 width,
  453. 453 height,
  454. 454 sx + 1,
  455. 455 sy,
  456. 456 )
  457. 457● let (_, cb2, cr2) = prog420_pixel_ycbcr(
  458. 458 data,
  459. 459 channels,
  460. 460 width,
  461. 461 height,
  462. 462 sx,
  463. 463 sy + 1,
  464. 464 )
  465. 465● let (_, cb3, cr3) = prog420_pixel_ycbcr(
  466. 466 data,
  467. 467 channels,
  468. 468 width,
  469. 469 height,
  470. 470 sx + 1,
  471. 471 sy + 1,
  472. 472 )
  473. 473 let o = py * 8 + px
  474. 474 block[o] = (cb0 + cb1 + cb2 + cb3) / 4
  475. 475 block_cr[o] = (cr0 + cr1 + cr2 + cr3) / 4
  476. 476 }
  477. 477 }
  478. 478 let cbase = (by * stride_c + bx) * 64
  479. 479● jpeg_progressive_quantize_block(
  480. 480 block, inv_chr, zz, tmp_i, shifted, dct_out, coefs_cb, cbase,
  481. 481 )
  482. 482● jpeg_progressive_quantize_block(
  483. 483 block_cr, inv_chr, zz, tmp_i, shifted, dct_out, coefs_cr, cbase,
  484. 484 )
  485. 485 }
  486. 486 }
  487. 487 let out : Array[Byte] = []
  488. 488● out.push(b'\xFF')
  489. 489● out.push(b'\xD8')
  490. 490 // ---- DQT
  491. 491● out.push(b'\xFF')
  492. 492● out.push(b'\xDB')
  493. 493● out.push(b'\x00')
  494. 494● out.push(b'\x84')
  495. 495● out.push(b'\x00')
  496. 496 for k in 0..<64 {
  497. 497● out.push(quant_lum[zz[k]].to_byte())
  498. 498 }
  499. 499● out.push(b'\x01')
  500. 500 for k in 0..<64 {
  501. 501● out.push(quant_chr[zz[k]].to_byte())
  502. 502 }
  503. 503 // ---- SOF2(Y 2×2、Cb/Cr 1×1)
  504. 504● out.push(b'\xFF')
  505. 505● out.push(b'\xC2')
  506. 506● out.push(b'\x00')
  507. 507● out.push(b'\x11')
  508. 508● out.push(b'\x08')
  509. 509● out.push(((height >> 8) & 0xFF).to_byte())
  510. 510● out.push((height & 0xFF).to_byte())
  511. 511● out.push(((width >> 8) & 0xFF).to_byte())
  512. 512● out.push((width & 0xFF).to_byte())
  513. 513● out.push(b'\x03')
  514. 514● out.push(b'\x01')
  515. 515● out.push(b'\x22')
  516. 516● out.push(b'\x00')
  517. 517● out.push(b'\x02')
  518. 518● out.push(b'\x11')
  519. 519● out.push(b'\x01')
  520. 520● out.push(b'\x03')
  521. 521● out.push(b'\x11')
  522. 522● out.push(b'\x01')
  523. 523 // ---- DHT:先给 DC 标准两张(AC 表按扫描逐条重建,紧跟各自 SOS)
  524. 524 let dc_dht : Array[Byte] = []
  525. 525● dc_dht.push(b'\x00')
  526. 526● for b in std_dc_lum_bits() {
  527. 527● dc_dht.push(b.to_byte())
  528. 528 }
  529. 529● for v in std_dc_lum_vals() {
  530. 530● dc_dht.push(v.to_byte())
  531. 531 }
  532. 532● dc_dht.push(b'\x01')
  533. 533● for b in std_dc_chr_bits() {
  534. 534● dc_dht.push(b.to_byte())
  535. 535 }
  536. 536● for v in std_dc_chr_vals() {
  537. 537● dc_dht.push(v.to_byte())
  538. 538 }
  539. 539● let dc_dht_len = 2 + dc_dht.length()
  540. 540● out.push(b'\xFF')
  541. 541● out.push(b'\xC4')
  542. 542● out.push(((dc_dht_len >> 8) & 0xFF).to_byte())
  543. 543● out.push((dc_dht_len & 0xFF).to_byte())
  544. 544 for b in dc_dht {
  545. 545● out.push(b)
  546. 546 }
  547. 547 // ---- 逐扫描:AC 扫描两遍(计频 → 建表 → 写 DHT → SOS → 位流)
  548. 548● let scratch_out : Array[Byte] = Array::make(1, b'\x00')
  549. 549 for scan in script {
  550. 550● let is_dc = scan.ss == 0
  551. 551 if is_dc && scan.ah == 0 {
  552. 552● let ids : Array[Byte] = []
  553. 553 let slots : Array[Byte] = []
  554. 554 for ci in scan.comps {
  555. 555● ids.push((ci + 1).to_byte())
  556. 556● slots.push(if ci == 0 { b'\x00' } else { b'\x11' })
  557. 557 }
  558. 558● jpeg_push_sos(
  559. 559 out,
  560. 560● ids.length(),
  561. 561 ids,
  562. 562 slots,
  563. 563 0,
  564. 564 0,
  565. 565 (scan.ah << 4) | scan.al,
  566. 566 )
  567. 567 let w = JpegBitWriter::{ out, bit_buf: 0, bit_cnt: 0, }
  568. 568● prog420_dc_first(
  569. 569 w,
  570. 570 dc_lum_enc,
  571. 571 dc_chr_enc,
  572. 572 coefs_y,
  573. 573 coefs_cb,
  574. 574 coefs_cr,
  575. 575 stride_y,
  576. 576 stride_c,
  577. 577 mcus_x,
  578. 578 mcus_y,
  579. 579 scan.al,
  580. 580 )
  581. 581● jpeg_flush_bits(w)
  582. 582● } else if is_dc {
  583. 583● let ids : Array[Byte] = []
  584. 584 let slots : Array[Byte] = []
  585. 585 for ci in scan.comps {
  586. 586● ids.push((ci + 1).to_byte())
  587. 587● slots.push(if ci == 0 { b'\x00' } else { b'\x11' })
  588. 588 }
  589. 589● jpeg_push_sos(
  590. 590 out,
  591. 591● ids.length(),
  592. 592 ids,
  593. 593 slots,
  594. 594 0,
  595. 595 0,
  596. 596 (scan.ah << 4) | scan.al,
  597. 597 )
  598. 598 let w = JpegBitWriter::{ out, bit_buf: 0, bit_cnt: 0, }
  599. 599● prog420_dc_refine(
  600. 600 w,
  601. 601 coefs_y,
  602. 602 coefs_cb,
  603. 603 coefs_cr,
  604. 604 stride_y,
  605. 605 stride_c,
  606. 606 mcus_x,
  607. 607 mcus_y,
  608. 608 scan.al,
  609. 609 )
  610. 610● jpeg_flush_bits(w)
  611. 611 } else {
  612. 612● let ci = scan.comps[0]
  613. 613 let (plane, stride, bx_max, by_max) = if ci == 0 {
  614. 614● (coefs_y, stride_y, y_fx, y_fy)
  615. 615● } else if ci == 1 {
  616. 616● (coefs_cb, stride_c, c_fx, c_fy)
  617. 617 } else {
  618. 618● (coefs_cr, stride_c, c_fx, c_fy)
  619. 619 }
  620. 620● let slot : Byte = if ci == 0 { b'\x00' } else { b'\x11' }
  621. 621● let id : Array[Byte] = [(ci + 1).to_byte()]
  622. 622 let slots : Array[Byte] = [slot]
  623. 623 if scan.ah == 0 {
  624. 624● let freq = Array::make(257, 0)
  625. 625● prog_ac_first_scan(
  626. 626 JpegBitWriter::{ out: scratch_out, bit_buf: 0, bit_cnt: 0, },
  627. 627 if ci == 0 {
  628. 628● dc_lum_enc
  629. 629 } else {
  630. 630● dc_chr_enc
  631. 631 },
  632. 632 freq,
  633. 633 plane,
  634. 634 stride,
  635. 635 bx_max,
  636. 636 by_max,
  637. 637 scan.ss,
  638. 638 scan.se,
  639. 639 scan.al,
  640. 640 )
  641. 641● let (bits, vals) = jpeg_gen_optimal_table(freq)
  642. 642● let enc = build_huffman_encoder(bits, vals)
  643. 643 let dht_data : Array[Byte] = []
  644. 644● dht_data.push(if ci == 0 { b'\x10' } else { b'\x11' })
  645. 645 for b in bits {
  646. 646● dht_data.push(b.to_byte())
  647. 647 }
  648. 648 for v in vals {
  649. 649● dht_data.push(v.to_byte())
  650. 650 }
  651. 651● let dht_len = 2 + dht_data.length()
  652. 652● out.push(b'\xFF')
  653. 653● out.push(b'\xC4')
  654. 654● out.push(((dht_len >> 8) & 0xFF).to_byte())
  655. 655● out.push((dht_len & 0xFF).to_byte())
  656. 656 for b in dht_data {
  657. 657● out.push(b)
  658. 658 }
  659. 659● jpeg_push_sos(
  660. 660 out,
  661. 661 1,
  662. 662 id,
  663. 663 slots,
  664. 664 scan.ss,
  665. 665 scan.se,
  666. 666 (scan.ah << 4) | scan.al,
  667. 667 )
  668. 668 let w = JpegBitWriter::{ out, bit_buf: 0, bit_cnt: 0, }
  669. 669● prog_ac_first_scan(
  670. 670 w,
  671. 671 enc,
  672. 672 [],
  673. 673 plane,
  674. 674 stride,
  675. 675 bx_max,
  676. 676 by_max,
  677. 677 scan.ss,
  678. 678 scan.se,
  679. 679 scan.al,
  680. 680 )
  681. 681● jpeg_flush_bits(w)
  682. 682 } else {
  683. 683● let freq = Array::make(257, 0)
  684. 684● prog_ac_refine_scan(
  685. 685 JpegBitWriter::{ out: scratch_out, bit_buf: 0, bit_cnt: 0, },
  686. 686 if ci == 0 {
  687. 687● dc_lum_enc
  688. 688 } else {
  689. 689● dc_chr_enc
  690. 690 },
  691. 691 freq,
  692. 692 plane,
  693. 693 stride,
  694. 694 bx_max,
  695. 695 by_max,
  696. 696 scan.ss,
  697. 697 scan.se,
  698. 698 scan.al,
  699. 699 )
  700. 700● let (bits, vals) = jpeg_gen_optimal_table(freq)
  701. 701● let enc = build_huffman_encoder(bits, vals)
  702. 702 let dht_data : Array[Byte] = []
  703. 703● dht_data.push(if ci == 0 { b'\x10' } else { b'\x11' })
  704. 704 for b in bits {
  705. 705● dht_data.push(b.to_byte())
  706. 706 }
  707. 707 for v in vals {
  708. 708● dht_data.push(v.to_byte())
  709. 709 }
  710. 710● let dht_len = 2 + dht_data.length()
  711. 711● out.push(b'\xFF')
  712. 712● out.push(b'\xC4')
  713. 713● out.push(((dht_len >> 8) & 0xFF).to_byte())
  714. 714● out.push((dht_len & 0xFF).to_byte())
  715. 715 for b in dht_data {
  716. 716● out.push(b)
  717. 717 }
  718. 718● jpeg_push_sos(
  719. 719 out,
  720. 720 1,
  721. 721 id,
  722. 722 slots,
  723. 723 scan.ss,
  724. 724 scan.se,
  725. 725 (scan.ah << 4) | scan.al,
  726. 726 )
  727. 727 let w = JpegBitWriter::{ out, bit_buf: 0, bit_cnt: 0, }
  728. 728● prog_ac_refine_scan(
  729. 729 w,
  730. 730 enc,
  731. 731 [],
  732. 732 plane,
  733. 733 stride,
  734. 734 bx_max,
  735. 735 by_max,
  736. 736 scan.ss,
  737. 737 scan.se,
  738. 738 scan.al,
  739. 739 )
  740. 740● jpeg_flush_bits(w)
  741. 741 }
  742. 742 }
  743. 743 }
  744. 744● out.push(b'\xFF')
  745. 745● out.push(b'\xD9')
  746. 746● Bytes::from_array(out)
  747. 747}