Skip to content

Commit

Permalink
fmt and refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
luke-rt committed Feb 10, 2022
1 parent cadff00 commit 033c020
Showing 5 changed files with 24 additions and 45 deletions.
2 changes: 1 addition & 1 deletion .rustfmt.toml
Original file line number Diff line number Diff line change
@@ -5,4 +5,4 @@ newline_style = "Unix"
use_small_heuristics = "Default"
reorder_imports = true
reorder_modules = true
max_width = 80
max_width = 100
30 changes: 12 additions & 18 deletions src/converter.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
use crate::error::Result;
use opencv::prelude::*;

pub const CHARS: [char; 11] =
[' ', ' ', '.', ':', '!', '+', '*', 'e', '$', '@', '8'];
pub const CHARS: [char; 11] = [' ', ' ', '.', ':', '!', '+', '*', 'e', '$', '@', '8'];

#[derive(Copy, Clone, Debug)]
pub enum Strategy {
@@ -15,47 +14,42 @@ pub fn convert_frame(frame: &Mat, strategy: Strategy) -> Result<String> {

for i in 0..frame.rows() {
for j in 0..frame.cols() {
let bgr: opencv::core::Vec3b =
*frame.at_2d::<opencv::core::Vec3b>(i, j)?;
res.push_str(&convert_pxl(bgr, strategy).unwrap());
let bgr: opencv::core::Vec3b = *frame.at_2d::<opencv::core::Vec3b>(i, j)?;
res.push_str(&convert_pxl(bgr, strategy));
}
res.push('\n');
}

Ok(res)
}

fn convert_pxl(bgr: opencv::core::Vec3b, strategy: Strategy) -> Result<String> {
fn convert_pxl(bgr: opencv::core::Vec3b, strategy: Strategy) -> String {
let b = *bgr.get(0).unwrap();
let g = *bgr.get(1).unwrap();
let r = *bgr.get(2).unwrap();

match strategy {
Strategy::Ascii => Ok(to_ascii(r, g, b, strategy)?.to_string()),
Strategy::ColorAscii => Ok(to_color_ascii(r, g, b)?),
Strategy::Ascii => to_ascii(r, g, b, strategy).to_string(),
Strategy::ColorAscii => to_color_ascii(r, g, b),
}
}

// conversion strategies
fn to_ascii(r: u8, g: u8, b: u8, strategy: Strategy) -> Result<char> {
fn to_ascii(r: u8, g: u8, b: u8, strategy: Strategy) -> char {
let brightness: f32;

match strategy {
Strategy::Ascii => {
brightness = 0.2126 * f32::from(r)
+ 0.7152 * f32::from(g)
+ 0.0722 * f32::from(b);
brightness = 0.2126 * f32::from(r) + 0.7152 * f32::from(g) + 0.0722 * f32::from(b);
}
Strategy::ColorAscii => {
brightness = 0.267 * f32::from(r)
+ 0.642 * f32::from(g)
+ 0.091 * f32::from(b);
brightness = 0.267 * f32::from(r) + 0.642 * f32::from(g) + 0.091 * f32::from(b);
}
}

Ok(CHARS[(10.0 * brightness / 255.0) as usize])
CHARS[(10.0 * brightness / 255.0) as usize]
}

fn to_color_ascii(r: u8, g: u8, b: u8) -> Result<String> {
Ok(String::from("hello world"))
fn to_color_ascii(r: u8, g: u8, b: u8) -> String {
String::from("hello world")
}
2 changes: 1 addition & 1 deletion src/error.rs
Original file line number Diff line number Diff line change
@@ -9,7 +9,7 @@ pub enum Error {

impl Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
match self {
Error::Io(io_error) => write!(f, "IO ERR: {io_error}"),
Error::Opencv(opencv_error) => write!(f, "{opencv_error}"),
Error::Msg(error) => write!(f, "ERR: {error}"),
7 changes: 2 additions & 5 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -7,9 +7,9 @@ use std::io::{self, Write};
use ansi_term::Colour::{Green, Red};
use clap::Parser;

mod cli;
mod converter;
mod error;
mod cli;
mod renderer;
mod validators;

@@ -20,9 +20,7 @@ pub fn main() {

let strategy = converter::Strategy::Ascii;

if let Err(e) =
renderer::render(&opts.file, opts.output.as_deref(), strategy)
{
if let Err(e) = renderer::render(&opts.file, opts.output.as_deref(), strategy) {
let stderr = io::stderr();
let mut handle = stderr.lock();
write!(
@@ -34,5 +32,4 @@ pub fn main() {
)
.unwrap();
}
return;
}
28 changes: 8 additions & 20 deletions src/renderer.rs
Original file line number Diff line number Diff line change
@@ -14,11 +14,7 @@ use terminal_size::{terminal_size, Height, Width};
use crate::converter;
use crate::error::{Error, Result};

pub fn render(
filename: &Path,
output: Option<&Path>,
strategy: converter::Strategy,
) -> Result<()> {
pub fn render(filename: &Path, output: Option<&Path>, strategy: converter::Strategy) -> Result<()> {
if let Some(p) = output {
render_to_file(filename, p, strategy)?;
} else {
@@ -29,15 +25,14 @@ pub fn render(
}

fn render_to_file(fin: &Path, fout: &Path, strategy: converter::Strategy) -> Result<()> {
let mut capture =
videoio::VideoCapture::from_file(fin.to_str().unwrap(), 0)?;
let mut capture = videoio::VideoCapture::from_file(fin.to_str().unwrap(), 0)?;
let frame_count: u64 = capture.get(videoio::CAP_PROP_FRAME_COUNT)? as u64;
let pb = ProgressBar::new(frame_count);

File::create(fout)?.write_all(
"#!/bin/bash\n# This file was auto-generated by asciiframe\necho -en '\033[2J' \n"
.as_bytes(),
)?;
"#!/bin/bash\n# This file was auto-generated by asciiframe\necho -en '\033[2J' \n"
.as_bytes(),
)?;

for _i in 0..frame_count {
let mut frame = Mat::default();
@@ -70,8 +65,7 @@ fn render_to_file(fin: &Path, fout: &Path, strategy: converter::Strategy) -> Res
}

fn render_to_stdout(filename: &Path, strategy: converter::Strategy) -> Result<()> {
let mut capture =
videoio::VideoCapture::from_file(filename.to_str().unwrap(), 0)?;
let mut capture = videoio::VideoCapture::from_file(filename.to_str().unwrap(), 0)?;
let frame_count: u64 = capture.get(videoio::CAP_PROP_FRAME_COUNT)? as u64;
let time_d: f32 = (1.0 / capture.get(videoio::CAP_PROP_FPS)?) as f32;
let stdout = io::stdout();
@@ -103,9 +97,7 @@ fn render_to_stdout(filename: &Path, strategy: converter::Strategy) -> Result<()

let elapsed = start.elapsed().unwrap().as_secs_f32();
if elapsed < time_d {
sleep(Duration::from_millis(
((time_d - elapsed) * 1000.0) as u64,
));
sleep(Duration::from_millis(((time_d - elapsed) * 1000.0) as u64));
}
} else {
return Err(Error::from("Unable to get terminal size"));
@@ -126,11 +118,7 @@ fn render_frame_stdout(
Ok(())
}

fn render_frame_to_file(
frame: &Mat,
strategy: converter::Strategy,
path: &Path,
) -> Result<()> {
fn render_frame_to_file(frame: &Mat, strategy: converter::Strategy, path: &Path) -> Result<()> {
let mut fout = OpenOptions::new().append(true).open(path)?;
fout.write_all(
format!(

0 comments on commit 033c020

Please sign in to comment.