use std:: { sync::mpsc, time::Instant, }; use eframe::egui; 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::SyncSender , recv: mpsc::Receiver , gui_ctx: egui::Context, send_to_gui: mpsc::SyncSender , capture: Option , ctl: Controller, } pub fn sleep_ms (ms: u64) { std::thread::sleep (std::time::Duration::from_millis (ms)); } impl Driver { pub fn new ( send: mpsc::SyncSender , recv: mpsc::Receiver , gui_ctx: egui::Context, send_to_gui: mpsc::SyncSender , ) -> Self { Self { send, recv, gui_ctx, send_to_gui, capture: Some (Capture::new ().unwrap ()), ctl: Controller::new (Instant::now ()), } } pub fn run (&mut self) { let pool = rayon::ThreadPoolBuilder::new().build().unwrap (); loop { match self.recv.recv().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)).unwrap (); self.gui_ctx.request_repaint(); }, MsgFromController::StartJpegDecoder (jpeg_frame) => { let send = self.send.clone (); pool.spawn (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.send (MsgToDriver::DecodedJpegToRgba (rgba)).unwrap (); }); }, MsgFromController::StartNetworkSend (jpeg) => { let send = self.send.clone (); pool.spawn (move || { sleep_ms (50); send.send (MsgToDriver::NetworkWriteFinished).unwrap (); }); }, MsgFromController::StartCapture => { let mut capture = self.capture.take ().unwrap (); let send = self.send.clone (); pool.spawn (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.send (MsgToDriver::GotCapture ((capture, frame))).unwrap (); }); } } } } } }