use image::DynamicImage;
use crate::common::errors::MyError;
use crate::pipeline::char_maps::{LONG1, LONG2, SHORT1, SHORT2};
use super::frames::FrameIterator;
use super::image_pipeline::ImagePipeline;
use std::sync::mpsc::{Receiver, SyncSender};
use std::thread;
use std::time::Duration;
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
enum State {
Running,
Paused,
Stopped,
}
pub struct Runner {
pipeline: ImagePipeline,
media: FrameIterator,
fps: u64,
state: State,
tx_frames: SyncSender<Option<String>>,
rx_controls: Receiver<Control>,
w_mod: u32,
char_maps: Vec<Vec<char>>,
last_frame: Option<DynamicImage>,
}
#[derive(Debug, PartialEq)]
pub enum Control {
PauseContinue,
Exit,
SetCharMap(u32),
Resize(u16, u16),
}
impl Runner {
pub fn init(
pipeline: ImagePipeline,
media: FrameIterator,
fps: u64,
tx_frames: SyncSender<Option<String>>,
rx_controls: Receiver<Control>,
w_mod: u32,
) -> Self {
let char_maps: Vec<Vec<char>> = vec![
pipeline.char_map.clone(),
SHORT1.to_string().chars().collect(),
SHORT2.to_string().chars().collect(),
LONG1.to_string().chars().collect(),
LONG2.to_string().chars().collect(),
];
Self {
pipeline,
media,
fps,
state: State::Running,
tx_frames,
rx_controls,
w_mod,
char_maps,
last_frame: None,
}
}
fn time_to_send_next_frame(&self, time_count: &mut std::time::Instant) -> bool {
if std::time::Instant::now()
.duration_since(*time_count)
.as_micros()
< 1_000_000_u64.checked_div(self.fps).unwrap_or(0).into()
{
return false;
}
*time_count += Duration::from_micros(1_000_000_u64.checked_div(self.fps).unwrap_or(0));
true
}
fn process_frame(&mut self, frame: &DynamicImage) -> String {
let procimage = self.pipeline.process(frame);
self.pipeline.to_ascii(&procimage)
}
pub fn run(&mut self) -> Result<(), MyError> {
let mut time_count = std::time::Instant::now();
while self.state != State::Stopped {
let frame_needs_refresh = self.process_control_commands();
if self.should_process_frame(&mut time_count) {
let frame = self.get_current_frame();
if let Ok(_) = self.tx_frames.try_send(None){
let string_out = self.process_current_frame(frame.as_ref(), frame_needs_refresh);
let _ = self.tx_frames.try_send(string_out); }
else{
thread::sleep(Duration::from_millis(10));
}
} else {
thread::sleep(Duration::from_millis(0));
}
}
Ok(())
}
fn process_control_commands(&mut self) -> bool {
let mut needs_refresh = false;
while let Ok(control) = self.rx_controls.recv_timeout(Duration::from_millis(0)) {
needs_refresh = true;
match control {
Control::PauseContinue => self.toggle_pause(),
Control::Exit => self.state = State::Stopped,
Control::Resize(width, height) => {
self.resize_pipeline(width, height);
}
Control::SetCharMap(char_map) => {
self.set_char_map(char_map);
}
}
}
needs_refresh
}
fn toggle_pause(&mut self) {
match self.state {
State::Running => self.state = State::Paused,
State::Paused => self.state = State::Running,
_ => {}
}
}
fn resize_pipeline(&mut self, width: u16, height: u16) {
let _ = self
.pipeline
.set_target_resolution((width / self.w_mod as u16).into(), height.into());
}
fn set_char_map(&mut self, char_map: u32) {
self.pipeline.char_map =
self.char_maps[(char_map % self.char_maps.len() as u32) as usize].clone();
}
fn should_process_frame(&self, time_count: &mut std::time::Instant) -> bool {
self.time_to_send_next_frame(time_count)
&& (self.state == State::Running || self.state == State::Paused)
}
fn get_current_frame(&mut self) -> Option<DynamicImage> {
match self.state {
State::Running => self.media.next(),
State::Paused | State::Stopped => self.last_frame.clone(),
}
}
fn process_current_frame(
&mut self,
frame: Option<&DynamicImage>,
refresh: bool,
) -> Option<String> {
match frame {
Some(frame) => {
self.last_frame = Some(frame.clone());
Some(self.process_frame(frame))
}
None => {
if self.last_frame.is_some() && refresh {
Some(self.process_frame(&self.last_frame.clone().unwrap()))
} else {
None
}
}
}
}
}