aboutsummaryrefslogtreecommitdiff
path: root/lvc/src/encode.rs
blob: 10f8c50f33c8bce1a92b9bd26681dd3b1206ac1f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
use crate::diff::{diff, pixel_diff};
use crate::split::split;
use crate::{Block, Frame, Ref, View, P2};

pub struct EncodeConfig {
    pub threshold: u32,
    pub max_block_size: usize,
    pub iters: usize,
}

pub fn encode(last_frame: &Frame, frame: &Frame, view: View, config: &EncodeConfig) -> Block {
    let view_area = view.size().area();
    if view_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);

    let att = 1. - attention(frame, view) as f32 * 0.000001;
    let thres = (config.threshold as f32 * att.clamp(0.2, 1.0)) as u32;

    for granularity in [4, 2, 1] {
        for _ in 0..config.iters {
            let (nd, nrp) = optimize_ref(last_frame, frame, view, d, r, granularity);
            if nd < d {
                r = nrp;
                d = nd;
            } else {
                break;
            }
        }
    }

    if d < thres {
        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)
}

pub fn attention(frame: &Frame, view: View) -> u32 {
    let mut k = 0;
    for y in view.a.y..view.b.y - 1 {
        for x in view.a.x..view.b.x - 1 {
            let p = P2 { x, y };
            k += pixel_diff(frame[p], frame[p + P2::X]).pow(2);
            k += pixel_diff(frame[p], frame[p + P2::Y]).pow(2);
        }
    }
    k
}