gstreamer-rs/examples/src/bin/appsink.rs

127 lines
3.2 KiB
Rust
Raw Normal View History

2017-08-01 18:44:01 +00:00
extern crate gstreamer as gst;
use gst::*;
extern crate gstreamer_app as gst_app;
use gst_app::*;
extern crate gstreamer_audio as gst_audio;
2017-08-01 18:44:01 +00:00
extern crate glib;
extern crate byte_slice_cast;
use byte_slice_cast::*;
2017-08-01 18:44:01 +00:00
use std::u64;
use std::i16;
use std::i32;
pub mod utils;
fn create_pipeline() -> Result<Pipeline, utils::ExampleError> {
gst::init().map_err(utils::ExampleError::InitFailed)?;
2017-08-01 18:44:01 +00:00
let pipeline = gst::Pipeline::new(None);
let src = utils::create_element("audiotestsrc")?;
let sink = utils::create_element("appsink")?;
pipeline
.add_many(&[&src, &sink])
.expect("Unable to add elements in the pipeline");
2017-08-01 18:44:01 +00:00
utils::link_elements(&src, &sink)?;
let appsink = sink.clone()
.dynamic_cast::<AppSink>()
.expect("Sink element is expected to be an appsink!");
2017-08-01 18:44:01 +00:00
appsink.set_caps(&Caps::new_simple(
"audio/x-raw",
&[
("format", &gst_audio::AUDIO_FORMAT_S16.to_string()),
2017-08-02 17:15:16 +00:00
("layout", &"interleaved"),
("channels", &(1i32)),
("rate", &IntRange::<i32>::new(1, i32::MAX)),
2017-08-01 18:44:01 +00:00
],
));
appsink.set_callbacks(AppSinkCallbacks::new(
/* eos */
|_| {},
/* new_preroll */
|_| FlowReturn::Ok,
/* new_samples */
|appsink| {
let sample = match appsink.pull_sample() {
None => return FlowReturn::Eos,
Some(sample) => sample,
};
let buffer = sample
.get_buffer()
.expect("Unable to extract buffer from the sample");
let map = buffer
.map_readable()
.expect("Unable to map buffer for reading");
let samples = if let Ok(samples) = map.as_slice().as_slice_of::<i16>() {
samples
} else {
return FlowReturn::Error;
};
let sum: f64 = samples
.iter()
2017-08-01 18:44:01 +00:00
.map(|sample| {
let f = (*sample as f64) / (i16::MAX as f64);
2017-08-01 18:44:01 +00:00
f * f
})
.sum();
let rms = (sum / (samples.len() as f64)).sqrt();
2017-08-01 18:44:01 +00:00
println!("rms: {}", rms);
FlowReturn::Ok
},
));
Ok(pipeline)
}
fn main_loop() -> Result<(), utils::ExampleError> {
let pipeline = create_pipeline()?;
2017-08-01 18:44:01 +00:00
utils::set_state(&pipeline, gst::State::Playing)?;
let bus = pipeline
.get_bus()
.expect("Pipeline without bus. Shouldn't happen!");
2017-08-01 18:44:01 +00:00
loop {
let msg = match bus.timed_pop(u64::MAX) {
None => break,
Some(msg) => msg,
};
match msg.view() {
MessageView::Eos(..) => break,
MessageView::Error(err) => {
utils::set_state(&pipeline, gst::State::Null)?;
return Err(utils::ExampleError::ElementError(
2017-08-01 18:44:01 +00:00
msg.get_src().get_path_string(),
err.get_error(),
err.get_debug().unwrap(),
));
2017-08-01 18:44:01 +00:00
}
_ => (),
}
}
utils::set_state(&pipeline, gst::State::Null)?;
Ok(())
}
fn main() {
match main_loop() {
Ok(r) => r,
Err(e) => eprintln!("Error! {}", e),
}
2017-08-01 18:44:01 +00:00
}