-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcanvas.rs
79 lines (64 loc) · 2.13 KB
/
canvas.rs
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
use std::slice;
use std::thread;
use std::time::Duration;
use crossbeam_channel::Receiver;
use sdl2::event::Event;
use sdl2::keyboard::Keycode;
use sdl2::pixels;
use sdl2::render::TextureAccess;
use sdl2::video::Window;
use sdl2::EventPump;
use crate::types;
pub type ThreadSafeFrame = types::FrameMsg;
pub fn create(
width: i32,
height: i32,
receiver: Receiver<ThreadSafeFrame>,
) -> thread::JoinHandle<()> {
thread::spawn(move || {
let ctx = sdl2::init().unwrap();
let video_subsystem = ctx.video().unwrap();
let window = video_subsystem
.window("instacam", width as u32, height as u32)
.position_centered()
.build()
.unwrap();
let mut event_pump = ctx.event_pump().unwrap();
render_loop(window, &mut event_pump, receiver);
})
}
fn render_loop(window: Window, event_pump: &mut EventPump, receiver: Receiver<ThreadSafeFrame>) {
let (width, height) = window.size();
let mut canvas = window.into_canvas().build().unwrap();
let creator = canvas.texture_creator();
canvas.set_draw_color(pixels::Color::RGB(0, 255, 255));
let mut texture = creator
.create_texture(
pixels::PixelFormatEnum::BGR24,
TextureAccess::Streaming,
width,
height,
)
.unwrap();
'running: loop {
let frame_msg = receiver.recv().expect("Failed to receive frame");
let frame = frame_msg.0;
let data = unsafe { slice::from_raw_parts((*frame).data[0], (width * height) as usize) };
let linesize = unsafe { (*frame).linesize[0] };
texture.update(None, data, linesize as usize).unwrap();
canvas.clear();
canvas.copy(&texture, None, None).unwrap();
canvas.present();
for event in event_pump.poll_iter() {
match event {
Event::Quit { .. }
| Event::KeyDown {
keycode: Some(Keycode::Escape),
..
} => break 'running,
_ => {}
}
}
thread::sleep(Duration::new(0, 1_000_000_000u32 / 60));
}
}