five_five_five/src/driver.rs

164 lines
5.0 KiB
Rust

/// This is where all the I/O and task spawning and joining happens
use std::
{
time::Instant,
};
use eframe::egui;
use tokio::sync::mpsc;
use crate::
{
capture::Capture,
controller::
{
Controller,
MsgFromController,
JpegFrame,
RgbaFrame,
},
};
pub enum MsgToDriver
{
GuiNeedsRgbaFrame,
DecodedJpegToRgba (RgbaFrame),
NetworkWriteFinished,
GotCapture ((Capture, JpegFrame)),
}
pub enum MsgToGui
{
NewRgbaFrame (RgbaFrame),
}
pub struct Driver
{
send: mpsc::Sender <MsgToDriver>,
recv: mpsc::Receiver <MsgToDriver>,
gui_ctx: egui::Context,
send_to_gui: mpsc::Sender <MsgToGui>,
capture: Option <Capture>,
ctl: Controller,
}
pub fn sleep_ms (ms: u64)
{
std::thread::sleep (std::time::Duration::from_millis (ms));
}
impl Driver
{
pub fn new (
send: mpsc::Sender <MsgToDriver>,
recv: mpsc::Receiver <MsgToDriver>,
gui_ctx: egui::Context,
send_to_gui: mpsc::Sender <MsgToGui>,
) -> Self
{
Self {
send,
recv,
gui_ctx,
send_to_gui,
capture: Some (Capture::new ().unwrap ()),
ctl: Controller::new (Instant::now ()),
}
}
pub async fn run (&mut self)
{
loop
{
match self.recv.recv().await.unwrap ()
{
MsgToDriver::GuiNeedsRgbaFrame =>
{
self.ctl.handle_gui_needs_frame ();
},
MsgToDriver::DecodedJpegToRgba (frame) =>
{
self.ctl.handle_rgba_frame (frame);
},
MsgToDriver::NetworkWriteFinished =>
{
self.ctl.handle_network_write_finished ();
},
MsgToDriver::GotCapture ((capture, jpeg)) =>
{
self.ctl.handle_capture (jpeg);
self.capture = Some (capture);
},
}
while let Some (msg) = self.ctl.poll ()
{
match msg
{
MsgFromController::RepaintGui (rgba_frame) =>
{
self.send_to_gui.send (MsgToGui::NewRgbaFrame (rgba_frame)).await.ok ();
self.gui_ctx.request_repaint();
},
MsgFromController::StartJpegDecoder (jpeg_frame) =>
{
let send = self.send.clone ();
tokio::task::spawn_blocking (move ||
{
// sleep_ms (500);
let mut decoder = zune_jpeg::JpegDecoder::new_with_options (&jpeg_frame.data, zune_core::options::DecoderOptions::new_fast().jpeg_set_out_colorspace(zune_core::colorspace::ColorSpace::RGBA));
decoder.decode_headers().unwrap ();
let mut rgba = vec![0u8;decoder.output_buffer_size().unwrap ()];
decoder.decode_into(&mut rgba).unwrap ();
let rgba = RgbaFrame
{
data: rgba,
capture_time: jpeg_frame.capture_time,
};
send.blocking_send (MsgToDriver::DecodedJpegToRgba (rgba)).ok ();
});
},
MsgFromController::StartNetworkSend (jpeg) =>
{
let send = self.send.clone ();
tokio::spawn (async move
{
sleep_ms (50);
send.send (MsgToDriver::NetworkWriteFinished).await.ok ();
});
},
MsgFromController::StartCapture =>
{
let mut capture = self.capture.take ().unwrap ();
let send = self.send.clone ();
tokio::task::spawn_blocking (move ||
{
let mut data = vec! [0u8; capture.size_image()];
capture.wait_for_frame(&mut data).unwrap ();
let frame = JpegFrame
{
data,
capture_time: Instant::now (),
};
// sleep_ms (500);
send.blocking_send (MsgToDriver::GotCapture ((capture, frame))).ok ();
});
}
}
}
}
}
}