pcengine_rust/
video.rs

1//! The frame/line clock and the picture capture (`video.py`).
2//!
3//! `Timeline` is the VCE's sync generator: it owns the line and frame counters on the board's one
4//! master-clock timeline and decides 262 or 263 lines per frame (C3). `Capture` turns each line into
5//! a row of 9-bit palette values (`-------GGGRRRBBB`), looking the VDC's pixel indices up in the
6//! colour table *as it stood at each dot*, so a mid-line palette write splits the line exactly where
7//! the CPU wrote it: that is what Covell's CPU test draws.
8//!
9//! Compare pictures at the 9-bit values, never at RGB (docs/vce.md).
10//!
11//! Differences forced by Rust: the `Timeline` and the `Capture` are handed the VCE where they
12//! need it (the reference holds a reference); the pixel path is the board's field, which mixes
13//! the VDC rows and hands `finish_line` the result; a finished frame is moved into
14//! `last_frame` (the reference aliases the row list, which it never touches again).
15
16use serde::{Deserialize, Serialize};
17
18use crate::machine::{
19    Machine, ACTIVE_LINES, FRAME_LINES_LONG, FRAME_LINES_SHORT, HSYNC_CLOCKS, LINE_CLOCKS,
20    TOP_BLANK_LINES, VSYNC_LINES,
21};
22use crate::sockets::VideoTiming;
23use crate::vce::Vce;
24
25#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
26pub struct Timeline {
27    lines_follow_vce_bit2: bool,
28    pub frame: i64,
29    pub frame_lines: i64,
30    pub line: i64,
31    pub line_start: i64,
32}
33
34impl Timeline {
35    /// Time zero is the start of line `start_line` of frame 0 (U1: the power-up phase of the
36    /// raster against the CPU is not published; MAME's CPU test trace starts at line 260).
37    /// `start_offset` puts time zero that many master clocks *into* the line instead.
38    pub fn new(
39        machine: &Machine,
40        vce: &Vce,
41        start_line: i64,
42        start_offset: i64,
43    ) -> Result<Timeline, String> {
44        let mut timeline = Timeline {
45            lines_follow_vce_bit2: machine.lines_follow_vce_bit2,
46            frame: 0,
47            frame_lines: 0,
48            line: start_line,
49            line_start: -start_offset,
50        };
51        timeline.frame_lines = timeline.lines_for_frame(vce);
52        if !(0..timeline.frame_lines).contains(&start_line) {
53            return Err(format!(
54                "start_line {start_line} outside the {}-line frame",
55                timeline.frame_lines
56            ));
57        }
58        Ok(timeline)
59    }
60
61    fn lines_for_frame(&self, vce: &Vce) -> i64 {
62        // C3: sampled where the frame starts, as Mednafen samples it where the vsync ends.
63        if self.lines_follow_vce_bit2 && !vce.bit2() {
64            return FRAME_LINES_SHORT;
65        }
66        FRAME_LINES_LONG
67    }
68
69    #[inline]
70    pub fn next_line_start(&self) -> i64 {
71        self.line_start + LINE_CLOCKS
72    }
73
74    pub fn in_vsync(&self) -> bool {
75        self.line >= self.frame_lines - VSYNC_LINES
76    }
77
78    pub fn timing(&self, vce: &Vce) -> VideoTiming {
79        VideoTiming {
80            frame: self.frame,
81            line: self.line,
82            start_mclk: self.line_start,
83            dot_divider: vce.dot_divider(),
84            frame_lines: self.frame_lines,
85            in_vsync: self.in_vsync(),
86        }
87    }
88
89    /// Step to the next line; at the end of a frame start the next and re-read the VCE.
90    pub fn advance(&mut self, vce: &Vce) {
91        self.line_start += LINE_CLOCKS;
92        self.line += 1;
93        if self.line >= self.frame_lines {
94            self.line = 0;
95            self.frame += 1;
96            self.frame_lines = self.lines_for_frame(vce);
97        }
98    }
99}
100
101/// The 242 active lines of a frame: `rows[i]` is the 9-bit palette values of line 14 + i.
102#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
103pub struct Frame {
104    pub number: i64,
105    pub rows: Vec<Vec<u16>>,
106    pub dividers: Vec<u8>,
107}
108
109#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
110pub struct Capture {
111    /// the colour table as the line capture has replayed it
112    shadow: Vec<u16>,
113    rows: Vec<Vec<u16>>,
114    dividers: Vec<u8>,
115    pub last_frame: Option<Frame>,
116}
117
118impl Capture {
119    pub fn new(vce: &Vce) -> Capture {
120        Capture {
121            shadow: vce.palette.clone(),
122            rows: Vec::new(),
123            dividers: Vec::new(),
124            last_frame: None,
125        }
126    }
127
128    /// Called once the row of a line has ended, with the row the pixel path made of the VDCs'.
129    ///
130    /// [emu: Mednafen vce.cpp] A row is the 1365 master clocks from the end of the line's
131    /// horizontal sync to the end of the next line's: dot 0 is the first dot after the sync, so
132    /// a 256-wide picture (HDS 2) starts at dot 32 and fits in the row. This is the same
133    /// raster as `timing.start_mclk`, shifted by `HSYNC_CLOCKS`.
134    pub fn finish_line(&mut self, timing: &VideoTiming, row: &[u16], vce: &mut Vce) {
135        let first = timing.start_mclk + HSYNC_CLOCKS;
136        let end = first + LINE_CLOCKS;
137        let div = timing.dot_divider;
138        let log = &mut vce.palette_log;
139        let mut used = 0;
140        while used < log.len() && log[used].0 < end {
141            used += 1;
142        }
143        let mut colours = Vec::with_capacity(row.len());
144        let mut pending = 0;
145        let shadow = &mut self.shadow;
146        // The fork: with no palette write inside the row, which is nearly every line, the
147        // colour table is the same at every dot and no dot's time is needed.
148        let split = if used == 0 { &row[..0] } else { row };
149        if used == 0 {
150            colours.extend(row.iter().map(|&pixel| {
151                // colour 0 of every palette shows the backdrop/overscan entry
152                let entry = if pixel & 0x0F == 0 {
153                    pixel & 0x100
154                } else {
155                    pixel
156                };
157                shadow[entry as usize]
158            }));
159        }
160        for (x, &pixel) in split.iter().enumerate() {
161            let when = first + x as i64 * div;
162            while pending < used && log[pending].0 <= when {
163                shadow[log[pending].1 as usize] = log[pending].2;
164                pending += 1;
165            }
166            let mut pixel = pixel;
167            if pixel & 0x0F == 0 {
168                // colour 0 of every palette shows the backdrop/overscan entry
169                pixel &= 0x100;
170            }
171            colours.push(shadow[pixel as usize]);
172        }
173        while pending < used {
174            shadow[log[pending].1 as usize] = log[pending].2;
175            pending += 1;
176        }
177        log.drain(..used);
178        if timing.line == 0 {
179            self.rows = Vec::new();
180            self.dividers = Vec::new();
181        }
182        if (TOP_BLANK_LINES..TOP_BLANK_LINES + ACTIVE_LINES).contains(&timing.line) {
183            self.rows.push(colours);
184            self.dividers.push(div as u8);
185            if self.rows.len() as i64 == ACTIVE_LINES {
186                self.last_frame = Some(Frame {
187                    number: timing.frame,
188                    rows: std::mem::take(&mut self.rows),
189                    dividers: std::mem::take(&mut self.dividers),
190                });
191            }
192        }
193    }
194}