use crate::diff::diff; use crate::split::split; use crate::{Block, Frame, Ref, View}; pub struct EncodeConfig { pub threshold: u32, pub max_block_size: usize, } pub fn encode(last_frame: &Frame, frame: &Frame, view: View, config: &EncodeConfig) -> Block { if view.size().area() > config.max_block_size { let [av, bv] = split(view); let (ab, bb) = rayon::join( || Box::new(encode(last_frame, frame, av, config)), || Box::new(encode(last_frame, frame, bv, config)), ); return Block::Split(ab, bb); } let mut r = Ref::default(); let mut d = diff([last_frame, frame], view, r); for granularity in [4, 2, 1] { for _ in 0..10 { let (nd, nrp) = optimize_ref(last_frame, frame, view, d, r, granularity); if nd < d { r = nrp; d = nd; } else { break; } } } if d < config.threshold { return Block::Ref(r); } else { Block::Lit(frame.export(view)) } } pub fn optimize_ref( last_frame: &Frame, frame: &Frame, view: View, mut d: u32, mut r: Ref, granularity: i32, ) -> (u32, Ref) { let mut n = |f: fn(&mut Ref, i32)| { let mut r2 = r; f(&mut r2, granularity); let d2 = diff([last_frame, frame], view, r2); if d2 < d { d = d2; r = r2; } }; n(|r, g| r.pos_off.x += g); n(|r, g| r.pos_off.x -= g); n(|r, g| r.pos_off.y += g); n(|r, g| r.pos_off.y -= g); n(|r, g| r.color_off.r += (g as i16) << 2); n(|r, g| r.color_off.r -= (g as i16) << 2); n(|r, g| r.color_off.g += (g as i16) << 2); n(|r, g| r.color_off.g -= (g as i16) << 2); n(|r, g| r.color_off.b += (g as i16) << 2); n(|r, g| r.color_off.b -= (g as i16) << 2); (d, r) }