image.vision\video\video_codec.mbt

93.3% · 111 / 119 points · 396 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/// # 视频编解码 video/video_codec
  3. 3///
  4. 4/// 图像处理库子模块
  5. 5/// 图像处理库子模块 Image processing library submodule
  6. 6// 视频编解码 — 帧内/帧间/熵编码
  7. 7// Video codec: intra-frame / inter-frame / entropy coding
  8. 8//
  9. 9// Phase 17 v392: 视频处理大扩展 — 视频编解码。
  10. 10
  11. 11///|
  12. 12/// 帧类型。
  13. 13/// 帧类型 Frame type.
  14. 14/// `#non_exhaustive` 表示未来可能添加新构造器
  15. 15#derive(Eq, @debug.Debug)
  16. 16#non_exhaustive
  17. 17pub(all) enum FrameType {
  18. 18 IFrame // 帧内编码
  19. 19 PFrame // 前向预测
  20. 20 BFrame // 双向预测
  21. 21}
  22. 22
  23. 23///|
  24. 24pub extend FrameType with @debug.Debug::{to_repr}
  25. 25
  26. 26///|
  27. 27pub extend FrameType with Eq::{not_equal, equal}
  28. 28
  29. 29///|
  30. 30/// 编码参数。
  31. 31/// 编解码参数 Codec parameters.
  32. 32#derive(Eq, @debug.Debug)
  33. 33pub(all) struct VideoCodecParams {
  34. 34 qp : Int32 // 量化参数 (1-50)
  35. 35 block_size : Int32 // 块大小 (通常 8 或 16)
  36. 36 search_range : Int32 // 运动搜索范围
  37. 37 iframe_interval : Int32 // I 帧间隔
  38. 38}
  39. 39
  40. 40///|
  41. 41pub extend VideoCodecParams with @debug.Debug::{to_repr}
  42. 42
  43. 43///|
  44. 44pub extend VideoCodecParams with Eq::{not_equal, equal}
  45. 45
  46. 46///|
  47. 47/// 编码帧。
  48. 48/// 编码帧 Encoded frame.
  49. 49#derive(Eq, @debug.Debug)
  50. 50pub(all) struct EncodedFrame {
  51. 51 frame_type : FrameType
  52. 52 data : Bytes // 压缩数据
  53. 53 motion_vectors : Array[Int32] // 运动矢量 (dx, dy 交替)
  54. 54 width : Int32
  55. 55 height : Int32
  56. 56 channels : Int32
  57. 57}
  58. 58
  59. 59///|
  60. 60pub extend EncodedFrame with @debug.Debug::{to_repr}
  61. 61
  62. 62///|
  63. 63pub extend EncodedFrame with Eq::{not_equal, equal}
  64. 64
  65. 65///|
  66. 66/// 编码视频。
  67. 67/// 编码视频 Encoded video.
  68. 68#derive(Eq, @debug.Debug)
  69. 69pub(all) struct EncodedVideo {
  70. 70 frames : Array[EncodedFrame]
  71. 71 params : VideoCodecParams
  72. 72 width : Int32
  73. 73 height : Int32
  74. 74 channels : Int32
  75. 75}
  76. 76
  77. 77///|
  78. 78pub extend EncodedVideo with @debug.Debug::{to_repr}
  79. 79
  80. 80///|
  81. 81pub extend EncodedVideo with Eq::{not_equal, equal}
  82. 82
  83. 83///|
  84. 84/// 默认编码参数。
  85. 85/// 默认编解码参数 Default codec parameters.
  86. 86pub fn default_video_codec_params() -> VideoCodecParams {
  87. 87● { qp: 10, block_size: 8, search_range: 8, iframe_interval: 10, }
  88. 88}
  89. 89
  90. 90///|
  91. 91/// 游程编码 (RLE)。
  92. 92/// 游程编码 Run-length encoding.
  93. 93pub fn rle_encode(data : Array[Int32]) -> Bytes {
  94. 94● let result : Array[Byte] = []
  95. 95● let n = data.length()
  96. 96 if n == 0 {
  97. 97● return Bytes::from_array(result)
  98. 98 }
  99. 99 let mut i = 0
  100. 100 while i < n {
  101. 101● let val = data[i]
  102. 102 let mut run = 1
  103. 103 while i + run < n && data[i + run] == val && run < 255 {
  104. 104● run = run + 1
  105. 105 }
  106. 106● result.push(run.to_byte())
  107. 107● result.push(val.clamp(min=0, max=255).to_byte())
  108. 108 i = i + run
  109. 109 }
  110. 110● Bytes::from_array(result)
  111. 111}
  112. 112
  113. 113///|
  114. 114/// 游程解码 (RLE)。
  115. 115/// 游程解码 Run-length decoding.
  116. 116pub fn rle_decode(data : Bytes) -> Array[Int32] {
  117. 117● let result : Array[Int32] = []
  118. 118● let n = data.length()
  119. 119 let mut i = 0
  120. 120 while i + 1 < n {
  121. 121● let run = data[i].to_int()
  122. 122● let val = data[i + 1].to_int()
  123. 123 for _ in 0..<run {
  124. 124● result.push(val)
  125. 125 }
  126. 126 i = i + 2
  127. 127 }
  128. 128 result
  129. 129}
  130. 130
  131. 131///|
  132. 132/// 量化。
  133. 133/// 量化 Quantization.
  134. 134pub fn quantize(values : Array[Int32], qp : Int32) -> Array[Int32] {
  135. 135● if qp <= 0 {
  136. 136● return values
  137. 137 }
  138. 138 let q = qp
  139. 139 let result : Array[Int32] = []
  140. 140 for v in values {
  141. 141● result.push((v + q / 2) / q)
  142. 142 }
  143. 143 result
  144. 144}
  145. 145
  146. 146///|
  147. 147/// 反量化。
  148. 148/// 反量化 Dequantization.
  149. 149pub fn dequantize(values : Array[Int32], qp : Int32) -> Array[Int32] {
  150. 150● if qp <= 0 {
  151. 151○ return values
  152. 152 }
  153. 153 let result : Array[Int32] = []
  154. 154 for v in values {
  155. 155● result.push(v * qp)
  156. 156 }
  157. 157 result
  158. 158}
  159. 159
  160. 160///|
  161. 161/// 帧内编码:将图像转为像素数组 + RLE 压缩。
  162. 162/// 帧内编码 Intra-frame encoding
  163. 163pub fn encode_frame_intra(
  164. 164 img : @types.Image,
  165. 165 params : VideoCodecParams,
  166. 166) -> EncodedFrame {
  167. 167● let pixels : Array[Int32] = []
  168. 168● for i in 0..<img.data.length() {
  169. 169● pixels.push(img.data[i].to_int())
  170. 170 }
  171. 171● let quantized = quantize(pixels, params.qp)
  172. 172● let compressed = rle_encode(quantized)
  173. 173 {
  174. 174 frame_type: IFrame,
  175. 175 data: compressed,
  176. 176 motion_vectors: [],
  177. 177 width: img.width,
  178. 178 height: img.height,
  179. 179 channels: img.channels,
  180. 180 }
  181. 181}
  182. 182
  183. 183///|
  184. 184/// 帧内解码。
  185. 185/// 帧内解码 Intra-frame decoding.
  186. 186pub fn decode_frame_intra(frame : EncodedFrame) -> @types.Image {
  187. 187● let quantized = rle_decode(frame.data)
  188. 188● let pixels = dequantize(
  189. 189 quantized,
  190. 190 frame.width * frame.height * frame.channels,
  191. 191 )
  192. 192 let data : Array[Byte] = []
  193. 193● let n = pixels.length()
  194. 194 for i in 0..<(frame.width * frame.height * frame.channels) {
  195. 195● if i < n {
  196. 196● data.push(pixels[i].clamp(min=0, max=255).to_byte())
  197. 197 } else {
  198. 198○ data.push((0 : Byte))
  199. 199 }
  200. 200 }
  201. 201 {
  202. 202 width: frame.width,
  203. 203 height: frame.height,
  204. 204 channels: frame.channels,
  205. 205● data: Bytes::from_array(data),
  206. 206 }
  207. 207}
  208. 208
  209. 209///|
  210. 210/// 计算运动矢量(简化块匹配)。
  211. 211/// 计算运动向量(简化块匹配) Compute motion vectors (simplified block matching).
  212. 212pub fn compute_motion_vectors(
  213. 213 current : @types.Image,
  214. 214 reference : @types.Image,
  215. 215 search_range : Int32,
  216. 216) -> Array[Int32] {
  217. 217● let vectors : Array[Int32] = []
  218. 218 let w = current.width
  219. 219 let h = current.height
  220. 220 let ch = current.channels
  221. 221 let block = 8
  222. 222 let mut by = 0
  223. 223 while by < h {
  224. 224● let mut bx = 0
  225. 225 while bx < w {
  226. 226● let mut best_dx = 0
  227. 227 let mut best_dy = 0
  228. 228 let mut best_sad = 999999999.0
  229. 229 for dy in [0, -search_range, search_range] {
  230. 230● for dx in [0, -search_range, search_range] {
  231. 231● let mut sad = 0.0
  232. 232 for py in 0..<block {
  233. 233● for px in 0..<block {
  234. 234● let cx = bx + px
  235. 235 let cy = by + py
  236. 236 if cx >= w || cy >= h {
  237. 237● continue
  238. 238 }
  239. 239 let rx = cx + dx
  240. 240 let ry = cy + dy
  241. 241 if rx < 0 || rx >= w || ry < 0 || ry >= h {
  242. 242● continue
  243. 243 }
  244. 244 let ci = (cy * w + cx) * ch
  245. 245 let ri = (ry * w + rx) * ch
  246. 246● let diff = current.data[ci].to_int() - reference.data[ri].to_int()
  247. 247● sad = sad + diff.to_double().abs()
  248. 248 }
  249. 249 }
  250. 250 if sad < best_sad {
  251. 251● best_sad = sad
  252. 252 best_dx = dx
  253. 253 best_dy = dy
  254. 254 }
  255. 255 }
  256. 256 }
  257. 257● vectors.push(best_dx)
  258. 258● vectors.push(best_dy)
  259. 259 bx = bx + block
  260. 260 }
  261. 261 by = by + block
  262. 262 }
  263. 263 vectors
  264. 264}
  265. 265
  266. 266///|
  267. 267/// 帧间编码:运动估计 + 残差编码。
  268. 268/// 帧间编码:运动估计 + 残差编码 Inter-frame encoding: motion estimation + residual coding.
  269. 269pub fn encode_frame_inter(
  270. 270 current : @types.Image,
  271. 271 reference : @types.Image,
  272. 272 params : VideoCodecParams,
  273. 273) -> EncodedFrame {
  274. 274● let vectors = compute_motion_vectors(current, reference, params.search_range)
  275. 275 // 残差 = 当前帧 - 运动补偿参考帧
  276. 276 let residuals : Array[Int32] = []
  277. 277 let w = current.width
  278. 278 let h = current.height
  279. 279 let ch = current.channels
  280. 280 for y in 0..<h {
  281. 281● for x in 0..<w {
  282. 282● for c in 0..<ch {
  283. 283● let ci = (y * w + x) * ch + c
  284. 284● let cur = current.data[ci].to_int()
  285. 285● let ref_val = reference.data[ci].to_int()
  286. 286● residuals.push(cur - ref_val + 128)
  287. 287 }
  288. 288 }
  289. 289 }
  290. 290● let quantized = quantize(residuals, params.qp)
  291. 291● let compressed = rle_encode(quantized)
  292. 292 {
  293. 293 frame_type: PFrame,
  294. 294 data: compressed,
  295. 295 motion_vectors: vectors,
  296. 296 width: w,
  297. 297 height: h,
  298. 298 channels: ch,
  299. 299 }
  300. 300}
  301. 301
  302. 302///|
  303. 303/// 帧间解码:运动补偿 + 残差。
  304. 304/// 帧间解码:运动补偿 + 残差 Inter-frame decoding: motion compensation + residual.
  305. 305pub fn decode_frame_inter(
  306. 306 frame : EncodedFrame,
  307. 307 reference : @types.Image,
  308. 308) -> @types.Image {
  309. 309● let quantized = rle_decode(frame.data)
  310. 310● let residuals = dequantize(
  311. 311 quantized,
  312. 312 frame.width * frame.height * frame.channels,
  313. 313 )
  314. 314 let data : Array[Byte] = []
  315. 315 let w = frame.width
  316. 316 let h = frame.height
  317. 317 let ch = frame.channels
  318. 318 for y in 0..<h {
  319. 319● for x in 0..<w {
  320. 320● for c in 0..<ch {
  321. 321● let i = (y * w + x) * ch + c
  322. 322● let ref_val = reference.data[i].to_int()
  323. 323◐ let res = if i < residuals.length() { residuals[i] - 128 } else { 0 }
  324. 324 let val = ref_val + res
  325. 325● data.push(val.clamp(min=0, max=255).to_byte())
  326. 326 }
  327. 327 }
  328. 328 }
  329. 329● { width: w, height: h, channels: ch, data: Bytes::from_array(data), }
  330. 330}
  331. 331
  332. 332///|
  333. 333/// 视频编码流水线。
  334. 334/// 视频编码管线 Video encoding pipeline.
  335. 335pub fn encode_video(
  336. 336 frames : Array[@types.Image],
  337. 337 params : VideoCodecParams,
  338. 338) -> EncodedVideo {
  339. 339● let encoded : Array[EncodedFrame] = []
  340. 340● let n = frames.length()
  341. 341 if n == 0 {
  342. 342● return { frames: encoded, params, width: 0, height: 0, channels: 0, }
  343. 343 }
  344. 344 let w = frames[0].width
  345. 345 let h = frames[0].height
  346. 346 let ch = frames[0].channels
  347. 347 for i in 0..<n {
  348. 348● if i % params.iframe_interval == 0 || i == 0 {
  349. 349● encoded.push(encode_frame_intra(frames[i], params))
  350. 350 } else {
  351. 351● encoded.push(encode_frame_inter(frames[i], frames[i - 1], params))
  352. 352 }
  353. 353 }
  354. 354 { frames: encoded, params, width: w, height: h, channels: ch, }
  355. 355}
  356. 356
  357. 357///|
  358. 358/// 视频解码流水线。
  359. 359/// 视频解码管线 Video decoding pipeline.
  360. 360pub fn decode_video(encoded : EncodedVideo) -> Array[@types.Image] {
  361. 361● let frames : Array[@types.Image] = []
  362. 362● let n = encoded.frames.length()
  363. 363 for i in 0..<n {
  364. 364● let frame = encoded.frames[i]
  365. 365 if frame.frame_type is IFrame {
  366. 366● frames.push(decode_frame_intra(frame))
  367. 367● } else if i > 0 {
  368. 368● let prev = decode_frame_intra(encoded.frames[i - 1])
  369. 369● frames.push(decode_frame_inter(frame, prev))
  370. 370 } else {
  371. 371○ frames.push(decode_frame_intra(frame))
  372. 372 }
  373. 373 }
  374. 374 frames
  375. 375}
  376. 376
  377. 377///|
  378. 378/// 计算压缩比。
  379. 379/// 计算压缩比 Compute compression ratio.
  380. 380pub fn compute_compression_ratio(
  381. 381 original : Array[@types.Image],
  382. 382 encoded : EncodedVideo,
  383. 383) -> Double {
  384. 384● let mut original_size = 0
  385. 385 for img in original {
  386. 386● original_size = original_size + img.data.length()
  387. 387 }
  388. 388 let mut encoded_size = 0
  389. 389 for frame in encoded.frames {
  390. 390● encoded_size = encoded_size + frame.data.length()
  391. 391 }
  392. 392 if encoded_size == 0 {
  393. 393○ return 0.0
  394. 394 }
  395. 395● original_size.to_double() / encoded_size.to_double()
  396. 396}