Clean code

This commit is contained in:
galicaster 2018-04-24 19:41:27 +02:00
parent 2d9feaa462
commit db5493d110
2 changed files with 102 additions and 648 deletions

View file

@ -1,4 +1,4 @@
#![allow(non_camel_case_types, non_upper_case_globals)] #![allow(non_camel_case_types, non_upper_case_globals, non_snake_case)]
use std::ptr; use std::ptr;

View file

@ -1,70 +1,40 @@
// Copyright (C) 2018 Sebastian Dröge <sebastian@centricular.com> #![allow(non_camel_case_types, non_upper_case_globals, non_snake_case)]
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use glib; use glib;
use gst; use gst;
use gst::prelude::*; use gst::prelude::*;
//use gst_audio;
use gst_video; use gst_video;
use gst_base::prelude::*; use gst_base::prelude::*;
use byte_slice_cast::*;
use gst_plugin::base_src::*; use gst_plugin::base_src::*;
use gst_plugin::element::*; use gst_plugin::element::*;
use gst_plugin::object::*; use gst_plugin::object::*;
use gst_plugin::properties::*; use gst_plugin::properties::*;
use std::ops::Rem;
use std::sync::Mutex; use std::sync::Mutex;
use std::{i32, u32}; use std::{i32, u32};
use num_traits::cast::NumCast;
use num_traits::float::Float;
use std::ptr; use std::ptr;
use std::ffi::{CStr, CString}; use std::ffi::{CStr, CString};
use ndilib::*; use ndilib::*;
// Default values of properties
const DEFAULT_SAMPLES_PER_BUFFER: u32 = 1024;
const DEFAULT_FREQ: u32 = 440;
const DEFAULT_VOLUME: f64 = 0.8;
const DEFAULT_MUTE: bool = false;
const DEFAULT_IS_LIVE: bool = false;
// Property value storage // Property value storage
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
struct Settings { struct Settings {
stream_name: String, stream_name: String,
samples_per_buffer: u32,
freq: u32,
volume: f64,
mute: bool,
is_live: bool,
} }
impl Default for Settings { impl Default for Settings {
fn default() -> Self { fn default() -> Self {
Settings { Settings {
stream_name: String::from("Fixed ndi stream name"), stream_name: String::from("Fixed ndi stream name"),
samples_per_buffer: DEFAULT_SAMPLES_PER_BUFFER,
freq: DEFAULT_FREQ,
volume: DEFAULT_VOLUME,
mute: DEFAULT_MUTE,
is_live: DEFAULT_IS_LIVE,
} }
} }
} }
// Metadata for the properties // Metadata for the properties
static PROPERTIES: [Property; 6] = [ static PROPERTIES: [Property; 1] = [
Property::String( Property::String(
"stream-name", "stream-name",
"Sream Name", "Sream Name",
@ -72,44 +42,6 @@ static PROPERTIES: [Property; 6] = [
None, None,
PropertyMutability::ReadWrite, PropertyMutability::ReadWrite,
), ),
Property::UInt(
"samples-per-buffer",
"Samples Per Buffer",
"Number of samples per output buffer",
(1, u32::MAX),
DEFAULT_SAMPLES_PER_BUFFER,
PropertyMutability::ReadWrite,
),
Property::UInt(
"freq",
"Frequency",
"Frequency",
(1, u32::MAX),
DEFAULT_FREQ,
PropertyMutability::ReadWrite,
),
Property::Double(
"volume",
"Volume",
"Output volume",
(0.0, 10.0),
DEFAULT_VOLUME,
PropertyMutability::ReadWrite,
),
Property::Boolean(
"mute",
"Mute",
"Mute",
DEFAULT_MUTE,
PropertyMutability::ReadWrite,
),
Property::Boolean(
"is-live",
"Is Live",
"(Pseudo) live output",
DEFAULT_IS_LIVE,
PropertyMutability::ReadWrite,
),
]; ];
// Stream-specific state, i.e. audio format configuration // Stream-specific state, i.e. audio format configuration
@ -117,9 +49,6 @@ static PROPERTIES: [Property; 6] = [
struct State { struct State {
info: Option<gst_video::VideoInfo>, info: Option<gst_video::VideoInfo>,
recv: Option<NdiInstance>, recv: Option<NdiInstance>,
// sample_offset: u64,
// sample_stop: Option<u64>,
// accumulator: f64,
} }
impl Default for State { impl Default for State {
@ -127,9 +56,6 @@ impl Default for State {
State { State {
info: None, info: None,
recv: None, recv: None,
// sample_offset: 0,
// sample_stop: None,
// accumulator: 0.0,
} }
} }
} }
@ -152,7 +78,7 @@ impl NdiSrc {
fn new(element: &BaseSrc) -> Box<BaseSrcImpl<BaseSrc>> { fn new(element: &BaseSrc) -> Box<BaseSrcImpl<BaseSrc>> {
// Initialize live-ness and notify the base class that // Initialize live-ness and notify the base class that
// we'd like to operate in Time format // we'd like to operate in Time format
element.set_live(DEFAULT_IS_LIVE); element.set_live(true);
element.set_format(gst::Format::Time); element.set_format(gst::Format::Time);
Box::new(Self { Box::new(Self {
@ -196,83 +122,39 @@ impl NdiSrc {
( (
"format", "format",
&gst::List::new(&[ &gst::List::new(&[
&gst_video::VideoFormat::Uyvy.to_string(), &gst_video::VideoFormat::Uyvy.to_string(),
&gst_video::VideoFormat::Rgb.to_string(), //&gst_video::VideoFormat::Rgb.to_string(),
&gst_video::VideoFormat::Gray8.to_string(), //&gst_video::VideoFormat::Gray8.to_string(),
]), ]),
),
// ("layout", &"interleaved"),
// ("rate", &gst::IntRange::<i32>::new(1, i32::MAX)),
// ("channels", &gst::IntRange::<i32>::new(1, i32::MAX)),
("width", &gst::IntRange::<i32>::new(0, i32::MAX)),
("height", &gst::IntRange::<i32>::new(0, i32::MAX)),
(
"framerate",
&gst::FractionRange::new(
gst::Fraction::new(0, 1),
gst::Fraction::new(i32::MAX, 1),
), ),
), ("width", &gst::IntRange::<i32>::new(0, i32::MAX)),
], ("height", &gst::IntRange::<i32>::new(0, i32::MAX)),
); (
// The src pad template must be named "src" for basesrc "framerate",
// and specific a pad that is always there &gst::FractionRange::new(
let src_pad_template = gst::PadTemplate::new( gst::Fraction::new(0, 1),
"src", gst::Fraction::new(i32::MAX, 1),
gst::PadDirection::Src, ),
gst::PadPresence::Always, ),
&caps, ],
); );
klass.add_pad_template(src_pad_template); // The src pad template must be named "src" for basesrc
// and specific a pad that is always there
// Install all our properties let src_pad_template = gst::PadTemplate::new(
klass.install_properties(&PROPERTIES); "src",
} gst::PadDirection::Src,
gst::PadPresence::Always,
fn process<F: Float + FromByteSlice>( &caps,
data: &mut [u8], );
accumulator_ref: &mut f64, klass.add_pad_template(src_pad_template);
freq: u32,
rate: u32, // Install all our properties
channels: u32, klass.install_properties(&PROPERTIES);
vol: f64,
) {
use std::f64::consts::PI;
// Reinterpret our byte-slice as a slice containing elements of the type
// we're interested in. GStreamer requires for raw audio that the alignment
// of memory is correct, so this will never ever fail unless there is an
// actual bug elsewhere.
let data = data.as_mut_slice_of::<F>().unwrap();
// Convert all our parameters to the target type for calculations
let vol: F = NumCast::from(vol).unwrap();
let freq = freq as f64;
let rate = rate as f64;
let two_pi = 2.0 * PI;
// We're carrying a accumulator with up to 2pi around instead of working
// on the sample offset. High sample offsets cause too much inaccuracy when
// converted to floating point numbers and then iterated over in 1-steps
let mut accumulator = *accumulator_ref;
let step = two_pi * freq / rate;
for chunk in data.chunks_mut(channels as usize) {
let value = vol * F::sin(NumCast::from(accumulator).unwrap());
for sample in chunk {
*sample = value;
}
accumulator += step;
if accumulator >= two_pi {
accumulator -= two_pi;
}
}
*accumulator_ref = accumulator;
} }
} }
// Virtual methods of GObject itself // Virtual methods of GObject itself
impl ObjectImpl<BaseSrc> for NdiSrc { impl ObjectImpl<BaseSrc> for NdiSrc {
// Called whenever a value of a property is changed. It can be called // Called whenever a value of a property is changed. It can be called
@ -298,70 +180,6 @@ impl ObjectImpl<BaseSrc> for NdiSrc {
let _ = let _ =
element.post_message(&gst::Message::new_latency().src(Some(&element)).build()); element.post_message(&gst::Message::new_latency().src(Some(&element)).build());
} }
Property::UInt("samples-per-buffer", ..) => {
let mut settings = self.settings.lock().unwrap();
let samples_per_buffer = value.get().unwrap();
gst_info!(
self.cat,
obj: &element,
"Changing samples-per-buffer from {} to {}",
settings.samples_per_buffer,
samples_per_buffer
);
settings.samples_per_buffer = samples_per_buffer;
drop(settings);
let _ =
element.post_message(&gst::Message::new_latency().src(Some(&element)).build());
}
Property::UInt("freq", ..) => {
let mut settings = self.settings.lock().unwrap();
let freq = value.get().unwrap();
gst_info!(
self.cat,
obj: &element,
"Changing freq from {} to {}",
settings.freq,
freq
);
settings.freq = freq;
}
Property::Double("volume", ..) => {
let mut settings = self.settings.lock().unwrap();
let volume = value.get().unwrap();
gst_info!(
self.cat,
obj: &element,
"Changing volume from {} to {}",
settings.volume,
volume
);
settings.volume = volume;
}
Property::Boolean("mute", ..) => {
let mut settings = self.settings.lock().unwrap();
let mute = value.get().unwrap();
gst_info!(
self.cat,
obj: &element,
"Changing mute from {} to {}",
settings.mute,
mute
);
settings.mute = mute;
}
Property::Boolean("is-live", ..) => {
let mut settings = self.settings.lock().unwrap();
let is_live = value.get().unwrap();
gst_info!(
self.cat,
obj: &element,
"Changing is-live from {} to {}",
settings.is_live,
is_live
);
settings.is_live = is_live;
}
_ => unimplemented!(), _ => unimplemented!(),
} }
} }
@ -377,26 +195,6 @@ impl ObjectImpl<BaseSrc> for NdiSrc {
//TODO to_value supongo que solo funciona con numeros //TODO to_value supongo que solo funciona con numeros
Ok(settings.stream_name.to_value()) Ok(settings.stream_name.to_value())
} }
Property::UInt("samples-per-buffer", ..) => {
let settings = self.settings.lock().unwrap();
Ok(settings.samples_per_buffer.to_value())
}
Property::UInt("freq", ..) => {
let settings = self.settings.lock().unwrap();
Ok(settings.freq.to_value())
}
Property::Double("volume", ..) => {
let settings = self.settings.lock().unwrap();
Ok(settings.volume.to_value())
}
Property::Boolean("mute", ..) => {
let settings = self.settings.lock().unwrap();
Ok(settings.mute.to_value())
}
Property::Boolean("is-live", ..) => {
let settings = self.settings.lock().unwrap();
Ok(settings.is_live.to_value())
}
_ => unimplemented!(), _ => unimplemented!(),
} }
} }
@ -404,21 +202,6 @@ impl ObjectImpl<BaseSrc> for NdiSrc {
// Virtual methods of gst::Element. We override none // Virtual methods of gst::Element. We override none
impl ElementImpl<BaseSrc> for NdiSrc { impl ElementImpl<BaseSrc> for NdiSrc {
fn change_state(
&self,
element: &BaseSrc,
transition: gst::StateChange,
) -> gst::StateChangeReturn {
// Configure live'ness once here just before starting the source
match transition {
gst::StateChange::ReadyToPaused => {
element.set_live(self.settings.lock().unwrap().is_live);
}
_ => (),
}
element.parent_change_state(transition)
}
} }
// Virtual methods of gst_base::BaseSrc // Virtual methods of gst_base::BaseSrc
@ -430,7 +213,6 @@ impl BaseSrcImpl<BaseSrc> for NdiSrc {
// We simply remember the resulting AudioInfo from the caps to be able to use this for knowing // We simply remember the resulting AudioInfo from the caps to be able to use this for knowing
// the sample rate, etc. when creating buffers // the sample rate, etc. when creating buffers
fn set_caps(&self, element: &BaseSrc, caps: &gst::CapsRef) -> bool { fn set_caps(&self, element: &BaseSrc, caps: &gst::CapsRef) -> bool {
use std::f64::consts::PI;
let info = match gst_video::VideoInfo::from_caps(caps) { let info = match gst_video::VideoInfo::from_caps(caps) {
None => return false, None => return false,
@ -442,47 +224,6 @@ impl BaseSrcImpl<BaseSrc> for NdiSrc {
// TODO Puede que falle si no creamos la estructura de cero, pero si lo hacemos no podemos poner recv a none // TODO Puede que falle si no creamos la estructura de cero, pero si lo hacemos no podemos poner recv a none
let mut state = self.state.lock().unwrap(); let mut state = self.state.lock().unwrap();
state.info = Some(info); state.info = Some(info);
// *state = State {
// info: Some(info),
// recv: Some(NdiInstance{recv: pNDI_recv}),
// };
// element.set_blocksize(info.bpf() * (*self.settings.lock().unwrap()).samples_per_buffer);
//
// let settings = &*self.settings.lock().unwrap();
// let mut state = self.state.lock().unwrap();
//
// // If we have no caps yet, any old sample_offset and sample_stop will be
// // in nanoseconds
// let old_rate = match state.info {
// Some(ref info) => info.rate() as u64,
// None => gst::SECOND_VAL,
// };
//
// // Update sample offset and accumulator based on the previous values and the
// // sample rate change, if any
// let old_sample_offset = state.sample_offset;
// let sample_offset = old_sample_offset
// .mul_div_floor(info.rate() as u64, old_rate)
// .unwrap();
//
// let old_sample_stop = state.sample_stop;
// let sample_stop =
// old_sample_stop.map(|v| v.mul_div_floor(info.rate() as u64, old_rate).unwrap());
//
// let accumulator =
// (sample_offset as f64).rem(2.0 * PI * (settings.freq as f64) / (info.rate() as f64));
//
// *state = State {
// info: Some(info),
// sample_offset: sample_offset,
// sample_stop: sample_stop,
// accumulator: accumulator,
// };
//
// drop(state);
//
// let _ = element.post_message(&gst::Message::new_latency().src(Some(element)).build());
true true
} }
@ -592,41 +333,6 @@ impl BaseSrcImpl<BaseSrc> for NdiSrc {
true true
} }
// fn query(&self, element: &BaseSrc, query: &mut gst::QueryRef) -> bool {
// use gst::QueryView;
//
// match query.view_mut() {
// // We only work in Push mode. In Pull mode, create() could be called with
// // arbitrary offsets and we would have to produce for that specific offset
// QueryView::Scheduling(ref mut q) => {
// q.set(gst::SchedulingFlags::SEQUENTIAL, 1, -1, 0);
// q.add_scheduling_modes(&[gst::PadMode::Push]);
// return true;
// }
// // In Live mode we will have a latency equal to the number of samples in each buffer.
// // We can't output samples before they were produced, and the last sample of a buffer
// // is produced that much after the beginning, leading to this latency calculation
// QueryView::Latency(ref mut q) => {
// let settings = &*self.settings.lock().unwrap();
// let state = self.state.lock().unwrap();
//
// if let Some(ref info) = state.info {
// let latency = gst::SECOND
// .mul_div_floor(settings.samples_per_buffer as u64, info.rate() as u64)
// .unwrap();
// gst_debug!(self.cat, obj: element, "Returning latency {}", latency);
// q.set(settings.is_live, latency, gst::CLOCK_TIME_NONE);
// return true;
// } else {
// return false;
// }
// }
// _ => (),
// }
// BaseSrcBase::parent_query(element, query)
// }
//Creates the audio buffers //Creates the audio buffers
fn create( fn create(
@ -639,11 +345,11 @@ impl BaseSrcImpl<BaseSrc> for NdiSrc {
// Keep a local copy of the values of all our properties at this very moment. This // Keep a local copy of the values of all our properties at this very moment. This
// ensures that the mutex is never locked for long and the application wouldn't // ensures that the mutex is never locked for long and the application wouldn't
// have to block until this function returns when getting/setting property values // have to block until this function returns when getting/setting property values
let settings = &*self.settings.lock().unwrap(); let _settings = &*self.settings.lock().unwrap();
// Get a locked reference to our state, i.e. the input and output AudioInfo // Get a locked reference to our state, i.e. the input and output AudioInfo
let mut state = self.state.lock().unwrap(); let state = self.state.lock().unwrap();
let info = match state.info { let _info = match state.info {
None => { None => {
gst_element_error!(element, gst::CoreError::Negotiation, ["Have no caps yet"]); gst_element_error!(element, gst::CoreError::Negotiation, ["Have no caps yet"]);
return Err(gst::FlowReturn::NotNegotiated); return Err(gst::FlowReturn::NotNegotiated);
@ -656,342 +362,90 @@ impl BaseSrcImpl<BaseSrc> for NdiSrc {
println!("pNDI_recv no encontrado"); println!("pNDI_recv no encontrado");
gst_element_error!(element, gst::CoreError::Negotiation, ["No encontramos ndi recv"]); gst_element_error!(element, gst::CoreError::Negotiation, ["No encontramos ndi recv"]);
return Err(gst::FlowReturn::NotNegotiated); return Err(gst::FlowReturn::NotNegotiated);
} }
Some(ref recv) => recv.clone(), Some(ref recv) => recv.clone(),
}; };
let pNDI_recv = recv.recv; let pNDI_recv = recv.recv;
unsafe{ unsafe{
// loop { // loop {
let video_frame: NDIlib_video_frame_v2_t = Default::default(); let video_frame: NDIlib_video_frame_v2_t = Default::default();
let audio_frame: NDIlib_audio_frame_v2_t = Default::default(); let audio_frame: NDIlib_audio_frame_v2_t = Default::default();
let metadata_frame: NDIlib_metadata_frame_t = Default::default(); let metadata_frame: NDIlib_metadata_frame_t = Default::default();
//TODO Solo hacemos el buffer cuando tengamos un frame de video //TODO Solo hacemos el buffer cuando tengamos un frame de video
let mut frame = false; let mut frame = false;
while !frame{ while !frame{
let frame_type = NDIlib_recv_capture_v2( let frame_type = NDIlib_recv_capture_v2(
pNDI_recv, pNDI_recv,
&video_frame, &video_frame,
&audio_frame, &audio_frame,
&metadata_frame, &metadata_frame,
1000, 1000,
); );
match frame_type { match frame_type {
NDIlib_frame_type_e::NDIlib_frame_type_video => { NDIlib_frame_type_e::NDIlib_frame_type_video => {
println!("Tengo video {:?}", video_frame); println!("Tengo video {:?}", video_frame);
frame = true; frame = true;
}
NDIlib_frame_type_e::NDIlib_frame_type_audio => {
println!("Tengo audio {:?}", audio_frame);
}
NDIlib_frame_type_e::NDIlib_frame_type_metadata => {
println!(
"Tengo metadata {} '{}'",
metadata_frame.length,
CStr::from_ptr(metadata_frame.p_data)
.to_string_lossy()
.into_owned(),
);
}
NDIlib_frame_type_e::NDIlib_frame_type_error => {
println!(
"Tengo error {} '{}'",
metadata_frame.length,
CStr::from_ptr(metadata_frame.p_data)
.to_string_lossy()
.into_owned(),
);
// break;
}
_ => println!("Tengo {:?}", frame_type),
} }
NDIlib_frame_type_e::NDIlib_frame_type_audio => {
println!("Tengo audio {:?}", audio_frame);
}
NDIlib_frame_type_e::NDIlib_frame_type_metadata => {
println!(
"Tengo metadata {} '{}'",
metadata_frame.length,
CStr::from_ptr(metadata_frame.p_data)
.to_string_lossy()
.into_owned(),
);
}
NDIlib_frame_type_e::NDIlib_frame_type_error => {
println!(
"Tengo error {} '{}'",
metadata_frame.length,
CStr::from_ptr(metadata_frame.p_data)
.to_string_lossy()
.into_owned(),
);
// break;
}
_ => println!("Tengo {:?}", frame_type),
} }
// }
let mut buffer = gst::Buffer::with_size(720 * 576 * 2).unwrap();
//let mut buffer = gst::Buffer::from_slice(video_frame.p_data).unwrap();
{
//rr let buffer = buffer.get_mut().unwrap();
//rr let pts: gst::ClockTime = (video_frame.timestamp as u64).into();
//rr let duration: gst::ClockTime = (334624).into();
//rr // buffer.set_pts(pts);
//rr //buffer.set_pts(pts);
//rr // buffer.set_duration(duration);
//rr // Map the buffer writable and create the actual samples
//rr let mut map = buffer.map_writable().unwrap();
//rr let mut data = map.as_slice();
//rr //data = &mut video_frame.p_data;
//rr let a = CStr::from_ptr(video_frame.p_data);
//rr data = a.to_bytes();
}
gst_debug!(self.cat, obj: element, "Produced buffer {:?}", buffer);
println!("Final create");
Ok(buffer)
} }
// }
// // If a stop position is set (from a seek), only produce samples up to that
// // point but at most samples_per_buffer samples per buffer
// let n_samples = if let Some(sample_stop) = state.sample_stop {
// if sample_stop <= state.sample_offset {
// gst_log!(self.cat, obj: element, "At EOS");
// return Err(gst::FlowReturn::Eos);
// }
//
// sample_stop - state.sample_offset
// } else {
// settings.samples_per_buffer as u64
// };
// Allocate a new buffer of the required size, update the metadata with the
// current timestamp and duration and then fill it according to the current
// caps
//TODO Set buffer size from data received from NDI
let mut buffer =
// gst::Buffer::with_size((n_samples as usize) * (info.bpf() as usize)).unwrap();
gst::Buffer::with_size(720 * 576 * 2).unwrap();
{
let buffer = buffer.get_mut().unwrap();
let pts: gst::ClockTime = (video_frame.timestamp as u64).into();
let duration: gst::ClockTime = (334624).into();
// buffer.set_pts(pts);
//buffer.set_pts(pts);
// buffer.set_duration(duration);
// Map the buffer writable and create the actual samples
let mut map = buffer.map_writable().unwrap();
let mut data = map.as_slice();
//data = &mut video_frame.p_data;
let a = CStr::from_ptr(video_frame.p_data);
data = a.to_bytes();
// // Calculate the current timestamp (PTS) and the next one,
// // and calculate the duration from the difference instead of
// // simply the number of samples to prevent rounding errors
// let pts = state
// .sample_offset
// .mul_div_floor(gst::SECOND_VAL, info.rate() as u64)
// .unwrap()
// .into();
// let next_pts: gst::ClockTime = (state.sample_offset + n_samples)
// .mul_div_floor(gst::SECOND_VAL, info.rate() as u64)
// .unwrap()
// .into();
// buffer.set_pts(pts);
// buffer.set_duration(next_pts - pts);
//
// // Map the buffer writable and create the actual samples
// let mut map = buffer.map_writable().unwrap();
// let data = map.as_mut_slice();
//
// if info.format() == gst_audio::AUDIO_FORMAT_F32 {
// Self::process::<f32>(
// data,
// &mut state.accumulator,
// settings.freq,
// info.rate(),
// info.channels(),
// settings.volume,
// );
// } else {
// Self::process::<f64>(
// data,
// &mut state.accumulator,
// settings.freq,
// info.rate(),
// info.channels(),
// settings.volume,
// );
// }
// }
// state.sample_offset += n_samples;
// drop(state);
//
// // If we're live, we are waiting until the time of the last sample in our buffer has
// // arrived. This is the very reason why we have to report that much latency.
// // A real live-source would of course only allow us to have the data available after
// // that latency, e.g. when capturing from a microphone, and no waiting from our side
// // would be necessary..
// //
// // Waiting happens based on the pipeline clock, which means that a real live source
// // with its own clock would require various translations between the two clocks.
// // This is out of scope for the tutorial though.
// if element.is_live() {
// let clock = match element.get_clock() {
// None => return Ok(buffer),
// Some(clock) => clock,
// };
//
// let segment = element
// .get_segment()
// .downcast::<gst::format::Time>()
// .unwrap();
// let base_time = element.get_base_time();
// let running_time = segment.to_running_time(buffer.get_pts() + buffer.get_duration());
//
// // The last sample's clock time is the base time of the element plus the
// // running time of the last sample
// let wait_until = running_time + base_time;
// if wait_until.is_none() {
// return Ok(buffer);
// }
//
// // Store the clock ID in our struct unless we're flushing anyway.
// // This allows to asynchronously cancel the waiting from unlock()
// // so that we immediately stop waiting on e.g. shutdown.
// let mut clock_wait = self.clock_wait.lock().unwrap();
// if clock_wait.flushing {
// gst_debug!(self.cat, obj: element, "Flushing");
// return Err(gst::FlowReturn::Flushing);
// }
//
// let id = clock.new_single_shot_id(wait_until).unwrap();
// clock_wait.clock_id = Some(id.clone());
// drop(clock_wait);
//
// gst_log!(
// self.cat,
// obj: element,
// "Waiting until {}, now {}",
// wait_until,
// clock.get_time()
// );
// let (res, jitter) = id.wait();
// gst_log!(
// self.cat,
// obj: element,
// "Waited res {:?} jitter {}",
// res,
// jitter
// );
// self.clock_wait.lock().unwrap().clock_id.take();
//
// // If the clock ID was unscheduled, unlock() was called
// // and we should return Flushing immediately.
// if res == gst::ClockReturn::Unscheduled {
// gst_debug!(self.cat, obj: element, "Flushing");
// return Err(gst::FlowReturn::Flushing);
// }
}
gst_debug!(self.cat, obj: element, "Produced buffer {:?}", buffer);
println!("Final create");
Ok(buffer)
}
} }
fn fixate(&self, element: &BaseSrc, caps: gst::Caps) -> gst::Caps {
// Fixate the caps. BaseSrc will do some fixation for us, but
// as we allow any rate between 1 and MAX it would fixate to 1. 1Hz
// is generally not a useful sample rate.
//
// We fixate to the closest integer value to 48kHz that is possible
// here, and for good measure also decide that the closest value to 1
// channel is good.
let mut caps = gst::Caps::truncate(caps);
{
let caps = caps.make_mut();
let s = caps.get_mut_structure(0).unwrap();
s.fixate_field_nearest_int("rate", 48_000);
s.fixate_field_nearest_int("channels", 1);
}
// Let BaseSrc fixate anything else for us. We could've alternatively have
// called Caps::fixate() here
element.parent_fixate(caps)
}
fn is_seekable(&self, _element: &BaseSrc) -> bool {
false
}
// fn do_seek(&self, element: &BaseSrc, segment: &mut gst::Segment) -> bool {
// // Handle seeking here. For Time and Default (sample offset) seeks we can
// // do something and have to update our sample offset and accumulator accordingly.
// //
// // Also we should remember the stop time (so we can stop at that point), and if
// // reverse playback is requested. These values will all be used during buffer creation
// // and for calculating the timestamps, etc.
//
// if segment.get_rate() < 0.0 {
// gst_error!(self.cat, obj: element, "Reverse playback not supported");
// return false;
// }
//
// let settings = *self.settings.lock().unwrap();
// let mut state = self.state.lock().unwrap();
//
// // We store sample_offset and sample_stop in nanoseconds if we
// // don't know any sample rate yet. It will be converted correctly
// // once a sample rate is known.
// let rate = match state.info {
// None => gst::SECOND_VAL,
// Some(ref info) => info.rate() as u64,
// };
//
// if let Some(segment) = segment.downcast_ref::<gst::format::Time>() {
// use std::f64::consts::PI;
//
// let sample_offset = segment
// .get_start()
// .unwrap()
// .mul_div_floor(rate, gst::SECOND_VAL)
// .unwrap();
//
// let sample_stop = segment
// .get_stop()
// .map(|v| v.mul_div_floor(rate, gst::SECOND_VAL).unwrap());
//
// let accumulator =
// (sample_offset as f64).rem(2.0 * PI * (settings.freq as f64) / (rate as f64));
//
// gst_debug!(
// self.cat,
// obj: element,
// "Seeked to {}-{:?} (accum: {}) for segment {:?}",
// sample_offset,
// sample_stop,
// accumulator,
// segment
// );
//
// *state = State {
// info: state.info.clone(),
// sample_offset: sample_offset,
// sample_stop: sample_stop,
// accumulator: accumulator,
// };
//
// true
// } else if let Some(segment) = segment.downcast_ref::<gst::format::Default>() {
// use std::f64::consts::PI;
//
// if state.info.is_none() {
// gst_error!(
// self.cat,
// obj: element,
// "Can only seek in Default format if sample rate is known"
// );
// return false;
// }
//
// let sample_offset = segment.get_start().unwrap();
// let sample_stop = segment.get_stop().0;
//
// let accumulator =
// (sample_offset as f64).rem(2.0 * PI * (settings.freq as f64) / (rate as f64));
//
// gst_debug!(
// self.cat,
// obj: element,
// "Seeked to {}-{:?} (accum: {}) for segment {:?}",
// sample_offset,
// sample_stop,
// accumulator,
// segment
// );
//
// *state = State {
// info: state.info.clone(),
// sample_offset: sample_offset,
// sample_stop: sample_stop,
// accumulator: accumulator,
// };
//
// true
// } else {
// gst_error!(
// self.cat,
// obj: element,
// "Can't seek in format {:?}",
// segment.get_format()
// );
//
// false
// }
// }
fn unlock(&self, element: &BaseSrc) -> bool { fn unlock(&self, element: &BaseSrc) -> bool {
// This should unblock the create() function ASAP, so we // This should unblock the create() function ASAP, so we