Seperated existing code

This commit is contained in:
Sebastian 2017-09-15 19:36:01 +02:00
parent d2bb513336
commit bfccaa419c
3 changed files with 157 additions and 115 deletions

43
src/config.rs Normal file
View File

@ -0,0 +1,43 @@
extern crate toml;
use std::fs::File;
use std::io::prelude::*;
#[derive(Debug, Deserialize, Clone)]
pub struct Config {
pub audio: AudioConfig,
pub output: OutputConfig,
}
#[derive(Debug, Deserialize, Clone)]
pub struct AudioConfig {
pub alsa_device: String,
pub rate: u32,
}
#[derive(Debug, Deserialize, Clone)]
pub struct OutputConfig {
pub directory: String,
pub prefix: String,
}
pub fn read_config(path: &str) -> Config {
let mut config_toml = String::new();
let mut file = match File::open(path) {
Ok(file) => file,
Err(_) => panic!("Could not find config file!"),
};
file.read_to_string(&mut config_toml)
.unwrap_or_else(|err| panic!("Error while reading config: [{}]", err));
let config: Config = toml::from_str(&config_toml).unwrap_or_else(|err| {
panic!("Error while parsing config: [{}]", err)
});
return config;
}

View File

@ -3,131 +3,27 @@ extern crate toml;
#[macro_use]
extern crate serde_derive;
extern crate gst;
extern crate itertools;
use std::fs::File;
use std::io::prelude::*;
use std::sync::mpsc;
use itertools::Itertools;
use sdl2::event::Event;
use sdl2::pixels;
mod config;
mod pipeline;
#[derive(Debug, Deserialize)]
struct Config {
audio: AudioConfig,
output: OutputConfig,
}
#[derive(Debug, Deserialize)]
struct AudioConfig {
alsa_device: String,
rate: u32,
}
#[derive(Debug, Deserialize)]
struct OutputConfig {
directory: String,
prefix: String,
}
fn read_config(path: &str) -> Config {
let mut config_toml = String::new();
let mut file = match File::open(path) {
Ok(file) => file,
Err(_) => panic!("Could not find config file!"),
};
file.read_to_string(&mut config_toml)
.unwrap_or_else(|err| panic!("Error while reading config: [{}]", err));
let config: Config = toml::from_str(&config_toml).unwrap_or_else(|err| {
panic!("Error while parsing config: [{}]", err)
});
return config;
}
fn handle_pipeline_events(bus_receiver : &mpsc::Receiver<gst::Message>) -> bool {
while let Ok(msg) = bus_receiver.try_recv() {
match msg.parse() {
gst::Message::StateChangedParsed { ref old, ref new, .. } => {
println!("element `{}` changed from {:?} to {:?}",
msg.src_name(), old, new);
}
gst::Message::ErrorParsed {ref error, ref debug, .. } => {
println!("error msg from element `{}`: {}, {}. Quitting",
msg.src_name(), error.message(), debug);
return true;
}
_ => {
println!("msg of type `{}` from element `{}`",
msg.type_name(), msg.src_name());
}
}
}
return false;
}
fn get_max_samples(appsink : &gst::appsink::AppSink) -> Result<(f32, f32), &str>{
match appsink.try_recv() {
Ok(gst::appsink::Message::NewSample(sample))
| Ok(gst::appsink::Message::NewPreroll(sample)) => {
if let Some(buffer) = sample.buffer() {
let (max0, max1) = buffer.map_read(|mapping| {
mapping.iter::<f32>().tuples().fold((0.0f32, 0.0f32), |(acc0, acc1), (sample0, sample1)| {
(acc0.max(sample0.abs()), acc1.max(sample1.abs()))
})
}).unwrap();
return Ok((max0, max1));
}
return Err("Unable to access samples");
}
Ok(gst::appsink::Message::Eos) => {
return Err("Got no sample when polling. EOS");
}
Err(mpsc::TryRecvError::Empty) => {
return Ok((0.0f32,0.0f32));
}
Err(mpsc::TryRecvError::Disconnected) => {
return Err("Appsink got disconnected")
}
}
}
const SCREEN_WIDTH: u32 = 160;
const SCREEN_HEIGHT: u32 = 128;
fn main() {
gst::init();
let config = read_config("rascam.toml");
let record_config = config::read_config("rascam.toml");
let mut recoding_pipeline = pipeline::RecordingPipeline::new(&record_config);
let pipeline_str = format!("alsasrc device={} ! audio/x-raw,rate={},channels=2 ! queue ! tee name=apptee ! audioconvert ! flacenc ! filesink location={}/{}.flac apptee. ! queue ! audioconvert ! appsink name=appsink0 caps=\"audio/x-raw,format=F32LE,channels=2\"",
config.audio.alsa_device,
config.audio.rate,
config.output.directory,
config.output.prefix);
println!("{}", pipeline_str);
let mut pipeline = gst::Pipeline::new_from_str(&pipeline_str).unwrap();
let mut mainloop = gst::MainLoop::new();
let mut bus = pipeline.bus().expect("Couldn't get bus from pipeline");
let bus_receiver = bus.receiver();
let appsink = pipeline
.get_by_name("appsink0")
.expect("Couldn't get appsink from pipeline");
let appsink = gst::AppSink::new_from_element(appsink);
/*
let sdl_context = sdl2::init().unwrap();
@ -144,14 +40,13 @@ fn main() {
canvas.present();
*/
mainloop.spawn();
pipeline.play();
recoding_pipeline.start();
loop {
if handle_pipeline_events(&bus_receiver) {
if !recoding_pipeline.handle_events() {
break;
}
let result = get_max_samples(& appsink);
let result = recoding_pipeline.get_max_samples();
match result {
Ok((max0, max1)) => {
println!("{} | {}", max0, max1);
@ -163,6 +58,5 @@ fn main() {
}
}
mainloop.quit();
recoding_pipeline.stop();
}

105
src/pipeline.rs Normal file
View File

@ -0,0 +1,105 @@
extern crate gst;
use std::sync::mpsc;
use itertools::Itertools;
use config;
pub struct RecordingPipeline {
pipeline : gst::Pipeline,
mainloop : gst::MainLoop,
bus_receiver : mpsc::Receiver<gst::Message>,
appsink : gst::AppSink,
}
impl RecordingPipeline {
pub fn new(record_config : &config::Config) -> RecordingPipeline {
let pipeline_str = format!("alsasrc device={} ! audio/x-raw,rate={},channels=2 ! \
queue ! tee name=apptee ! audioconvert ! flacenc ! filesink location={}/{}.flac \
apptee. ! queue ! audioconvert ! appsink name=appsink0 caps=\"audio/x-raw,format=F32LE,channels=2\"",
record_config.audio.alsa_device,
record_config.audio.rate,
record_config.output.directory,
record_config.output.prefix);
println!("{}", pipeline_str);
let pipeline = gst::Pipeline::new_from_str(&pipeline_str).unwrap();
let mainloop = gst::MainLoop::new();
let mut bus = pipeline.bus().expect("Couldn't get bus from pipeline");
let bus_receiver = bus.receiver();
let appsink_element = pipeline
.get_by_name("appsink0")
.expect("Couldn't get appsink from pipeline");
let appsink = gst::AppSink::new_from_element(appsink_element);
RecordingPipeline {
pipeline : pipeline,
mainloop : mainloop,
bus_receiver : bus_receiver,
appsink : appsink,
}
}
pub fn start(&mut self) {
self.mainloop.spawn();
self.pipeline.play();
}
pub fn stop(&mut self) {
self.pipeline.set_null_state();
self.mainloop.quit();
}
pub fn handle_events(&mut self) -> bool {
while let Ok(msg) = self.bus_receiver.try_recv() {
match msg.parse() {
gst::Message::StateChangedParsed { ref old, ref new, .. } => {
println!("element `{}` changed from {:?} to {:?}",
msg.src_name(), old, new);
}
gst::Message::ErrorParsed {ref error, ref debug, .. } => {
println!("error msg from element `{}`: {}, {}. Quitting",
msg.src_name(), error.message(), debug);
return false;
}
_ => {
println!("msg of type `{}` from element `{}`",
msg.type_name(), msg.src_name());
}
}
}
return true;
}
pub fn get_max_samples(&mut self) -> Result<(f32, f32), &str>{
match self.appsink.try_recv() {
Ok(gst::appsink::Message::NewSample(sample))
| Ok(gst::appsink::Message::NewPreroll(sample)) => {
if let Some(buffer) = sample.buffer() {
let (max0, max1) = buffer.map_read(|mapping| {
mapping.iter::<f32>().tuples().fold((0.0f32, 0.0f32), |(acc0, acc1), (sample0, sample1)| {
(acc0.max(sample0.abs()), acc1.max(sample1.abs()))
})
}).unwrap();
return Ok((max0, max1));
}
return Err("Unable to access samples");
}
Ok(gst::appsink::Message::Eos) => {
return Err("Got no sample when polling. EOS");
}
Err(mpsc::TryRecvError::Empty) => {
return Ok((0.0f32,0.0f32));
}
Err(mpsc::TryRecvError::Disconnected) => {
return Err("Appsink got disconnected")
}
}
}
}