Commit 56319f92 authored by Sebastian Dröge's avatar Sebastian Dröge 🍵

Move subclassing infrastructure into the main bindings

And port Element bindings to the new infrastructure.
parent d6ce094c
......@@ -312,6 +312,7 @@ status = "generate"
[[object]]
name = "Gst.Element"
subclassing = true
status = "generate"
[[object.function]]
name = "make_from_uri"
......
......@@ -47,6 +47,7 @@ dox = ["gstreamer-sys/dox", "glib/dox", "futures", "ser_de"]
futures = ["futures-core-preview"]
ser_de = ["num-rational/serde", "serde", "serde_bytes", "serde_derive"]
default-features = []
subclassing = ["glib/subclassing"]
[badges]
gitlab = { repository = "https://gitlab.freedesktop.org/gstreamer/gstreamer-rs", branch = "master" }
......@@ -33,8 +33,10 @@ use std::mem;
use std::mem::transmute;
use std::ptr;
use ElementClass;
glib_wrapper! {
pub struct Element(Object<ffi::GstElement, ffi::GstElementClass>): Object;
pub struct Element(Object<ffi::GstElement, ffi::GstElementClass, ElementClass>): Object;
match fn {
get_type => || ffi::gst_element_get_type(),
......
......@@ -16,7 +16,7 @@ use glib::translate::FromGlibPtrBorrow;
use glib::translate::{
from_glib, from_glib_full, from_glib_none, FromGlib, FromGlibPtrContainer, ToGlib, ToGlibPtr,
};
use glib::IsA;
use glib::{IsA, IsClassFor};
use miniobject::MiniObject;
use Event;
use Format;
......@@ -29,6 +29,7 @@ use SpecificFormattedValue;
use std::ffi::CStr;
use std::mem;
use std::ops;
use libc;
......@@ -92,6 +93,8 @@ impl FromGlib<libc::c_ulong> for NotifyWatchId {
}
pub trait ElementExtManual {
fn get_element_class(&self) -> &ElementClass;
fn query(&self, query: &mut QueryRef) -> bool;
fn send_event(&self, event: Event) -> bool;
......@@ -192,6 +195,14 @@ pub trait ElementExtManual {
}
impl<O: IsA<Element>> ElementExtManual for O {
fn get_element_class(&self) -> &ElementClass {
unsafe {
let klass = (*(self.to_glib_none().0 as *mut gobject_ffi::GTypeInstance)).g_class
as *const ElementClass;
&*klass
}
}
fn query(&self, query: &mut QueryRef) -> bool {
unsafe {
from_glib(ffi::gst_element_query(
......@@ -211,41 +222,15 @@ impl<O: IsA<Element>> ElementExtManual for O {
}
fn get_metadata<'a>(&self, key: &str) -> Option<&'a str> {
unsafe {
let klass = (*(self.to_glib_none().0 as *mut gobject_ffi::GTypeInstance)).g_class
as *mut ffi::GstElementClass;
let ptr = ffi::gst_element_class_get_metadata(klass, key.to_glib_none().0);
if ptr.is_null() {
None
} else {
Some(CStr::from_ptr(ptr).to_str().unwrap())
}
}
self.get_element_class().get_metadata(key)
}
fn get_pad_template(&self, name: &str) -> Option<PadTemplate> {
unsafe {
let klass = (*(self.to_glib_none().0 as *mut gobject_ffi::GTypeInstance)).g_class
as *mut ffi::GstElementClass;
from_glib_none(ffi::gst_element_class_get_pad_template(
klass,
name.to_glib_none().0,
))
}
self.get_element_class().get_pad_template(name)
}
fn get_pad_template_list(&self) -> Vec<PadTemplate> {
unsafe {
let klass = (*(self.to_glib_none().0 as *mut gobject_ffi::GTypeInstance)).g_class
as *mut ffi::GstElementClass;
FromGlibPtrContainer::from_glib_none(ffi::gst_element_class_get_pad_template_list(
klass,
))
}
self.get_element_class().get_pad_template_list()
}
fn message_full<T: ::MessageErrorDomain>(
......@@ -614,6 +599,67 @@ impl<O: IsA<Element>> ElementExtManual for O {
}
}
#[repr(C)]
pub struct ElementClass(ffi::GstElementClass);
unsafe impl IsClassFor for ElementClass {
type Instance = ::Element;
}
unsafe impl Send for ElementClass {}
unsafe impl Sync for ElementClass {}
impl ops::Deref for ElementClass {
type Target = glib::ObjectClass;
fn deref(&self) -> &Self::Target {
self.upcast_ref()
}
}
impl ops::DerefMut for ElementClass {
fn deref_mut(&mut self) -> &mut Self::Target {
self.upcast_ref_mut()
}
}
impl ElementClass {
pub fn get_metadata<'a>(&self, key: &str) -> Option<&'a str> {
unsafe {
let klass = self as *const _ as *const ffi::GstElementClass;
let ptr = ffi::gst_element_class_get_metadata(klass as *mut _, key.to_glib_none().0);
if ptr.is_null() {
None
} else {
Some(CStr::from_ptr(ptr).to_str().unwrap())
}
}
}
pub fn get_pad_template(&self, name: &str) -> Option<PadTemplate> {
unsafe {
let klass = self as *const _ as *const ffi::GstElementClass;
from_glib_none(ffi::gst_element_class_get_pad_template(
klass as *mut _,
name.to_glib_none().0,
))
}
}
pub fn get_pad_template_list(&self) -> Vec<PadTemplate> {
unsafe {
let klass = self as *const _ as *const ffi::GstElementClass;
FromGlibPtrContainer::from_glib_none(ffi::gst_element_class_get_pad_template_list(
klass as *mut _,
))
}
}
}
lazy_static! {
pub static ref ELEMENT_METADATA_AUTHOR: &'static str = unsafe {
CStr::from_ptr(ffi::GST_ELEMENT_METADATA_AUTHOR)
......
......@@ -16,12 +16,17 @@ extern crate cfg_if;
extern crate lazy_static;
extern crate libc;
extern crate glib_sys as glib_ffi;
extern crate gobject_sys as gobject_ffi;
extern crate gstreamer_sys as ffi;
// Re-exported for the subclass gst_plugin_define! macro
#[doc(hidden)]
pub extern crate glib_sys as glib_ffi;
#[doc(hidden)]
pub extern crate gobject_sys as gobject_ffi;
#[doc(hidden)]
pub extern crate gstreamer_sys as ffi;
#[macro_use]
extern crate glib;
#[doc(hidden)]
pub extern crate glib;
extern crate num_rational;
......@@ -143,6 +148,7 @@ pub use promise::*;
mod bin;
mod bus;
mod element;
pub use element::ElementClass;
// OS dependent Bus extensions (also import the other plateform mod for doc)
#[cfg(any(feature = "v1_14", feature = "dox"))]
......@@ -330,3 +336,7 @@ pub mod prelude {
}
mod utils;
#[macro_use]
#[cfg(feature = "subclassing")]
pub mod subclass;
This diff is collapsed.
// Copyright (C) 2016-2018 Sebastian Dröge <sebastian@centricular.com>
//
// 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 std::error::Error;
use std::fmt::Error as FmtError;
use std::fmt::{Display, Formatter};
use ErrorMessage;
use FlowReturn;
#[macro_export]
macro_rules! gst_panic_to_error(
($element:expr, $panicked:expr, $ret:expr, $code:block) => {{
use std::panic::{self, AssertUnwindSafe};
use std::sync::atomic::Ordering;
use $crate::ElementExtManual;
if $panicked.load(Ordering::Relaxed) {
$element.post_error_message(&gst_error_msg!($crate::LibraryError::Failed, ["Panicked"]));
$ret
} else {
let result = panic::catch_unwind(AssertUnwindSafe(|| $code));
match result {
Ok(result) => result,
Err(err) => {
$panicked.store(true, Ordering::Relaxed);
if let Some(cause) = err.downcast_ref::<&str>() {
$element.post_error_message(&gst_error_msg!($crate::LibraryError::Failed, ["Panicked: {}", cause]));
} else if let Some(cause) = err.downcast_ref::<String>() {
$element.post_error_message(&gst_error_msg!($crate::LibraryError::Failed, ["Panicked: {}", cause]));
} else {
$element.post_error_message(&gst_error_msg!($crate::LibraryError::Failed, ["Panicked"]));
}
$ret
}
}
}
}};
);
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum FlowError {
Flushing,
Eos,
NotNegotiated(ErrorMessage),
Error(ErrorMessage),
}
impl From<FlowError> for FlowReturn {
fn from(err: FlowError) -> Self {
FlowReturn::from(&err)
}
}
impl<'a> From<&'a FlowError> for FlowReturn {
fn from(err: &FlowError) -> FlowReturn {
match *err {
FlowError::Flushing => FlowReturn::Flushing,
FlowError::Eos => FlowReturn::Eos,
FlowError::NotNegotiated(..) => FlowReturn::NotNegotiated,
FlowError::Error(..) => FlowReturn::Error,
}
}
}
impl Display for FlowError {
fn fmt(&self, f: &mut Formatter) -> Result<(), FmtError> {
match *self {
FlowError::Flushing | FlowError::Eos => f.write_str(self.description()),
FlowError::NotNegotiated(ref m) => {
f.write_fmt(format_args!("{}: {}", self.description(), m))
}
FlowError::Error(ref m) => f.write_fmt(format_args!("{}: {}", self.description(), m)),
}
}
}
impl Error for FlowError {
fn description(&self) -> &str {
match *self {
FlowError::Flushing => "Flushing",
FlowError::Eos => "Eos",
FlowError::NotNegotiated(..) => "Not Negotiated",
FlowError::Error(..) => "Error",
}
}
}
// Copyright (C) 2016-2018 Sebastian Dröge <sebastian@centricular.com>
// 2016 Luis de Bethencourt <luisbg@osg.samsung.com>
//
// 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.
#![cfg_attr(feature = "cargo-clippy", allow(cast_ptr_alignment))]
#[macro_use]
pub mod error;
#[macro_use]
pub mod plugin;
pub mod element;
pub mod prelude {
pub use super::element::{ElementClassSubclassExt, ElementImpl, ElementImplExt};
pub use super::PanicPoison;
pub use glib::subclass::prelude::*;
}
use self::prelude::*;
use glib;
use std::sync::atomic::AtomicBool;
#[repr(C)]
pub struct ElementInstanceStruct<T: ObjectSubclass> {
parent: <T::ParentType as glib::wrapper::Wrapper>::GlibType,
panicked: AtomicBool,
}
unsafe impl<T: ObjectSubclass> InstanceStruct for ElementInstanceStruct<T> {
type Type = T;
}
pub trait PanicPoison {
fn panicked(&self) -> &AtomicBool;
}
impl<T: ObjectSubclass> PanicPoison for ElementInstanceStruct<T> {
fn panicked(&self) -> &AtomicBool {
&self.panicked
}
}
// Copyright (C) 2016-2018 Sebastian Dröge <sebastian@centricular.com>
//
// 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.
#[macro_export]
macro_rules! gst_plugin_define(
($name:expr, $description:expr, $plugin_init:ident,
$version:expr, $license:expr, $source:expr,
$package:expr, $origin:expr, $release_datetime:expr) => {
pub mod plugin_desc {
use $crate::glib::translate::{from_glib_borrow, ToGlib, from_glib};
const MAJOR_VERSION: i32 = 1;
const MINOR_VERSION: i32 = 8;
// Not using c_char here because it requires the libc crate
#[allow(non_camel_case_types)]
type c_char = i8;
#[repr(C)]
pub struct GstPluginDesc($crate::ffi::GstPluginDesc);
unsafe impl Sync for GstPluginDesc {}
#[no_mangle]
#[allow(non_upper_case_globals)]
pub static gst_plugin_desc: GstPluginDesc = GstPluginDesc($crate::ffi::GstPluginDesc {
major_version: MAJOR_VERSION,
minor_version: MINOR_VERSION,
name: $name as *const u8 as *const c_char,
description: $description as *const u8 as *const c_char,
plugin_init: Some(plugin_init_trampoline),
version: $version as *const u8 as *const c_char,
license: $license as *const u8 as *const c_char,
source: $source as *const u8 as *const c_char,
package: $package as *const u8 as *const c_char,
origin: $origin as *const u8 as *const c_char,
release_datetime: $release_datetime as *const u8 as *const c_char,
_gst_reserved: [0 as $crate::glib_ffi::gpointer; 4],
});
pub fn plugin_register_static() -> bool {
unsafe {
from_glib($crate::ffi::gst_plugin_register_static(
MAJOR_VERSION,
MINOR_VERSION,
$name as *const u8 as *const c_char,
$description as *const u8 as *const c_char,
Some(plugin_init_trampoline),
$version as *const u8 as *const c_char,
$license as *const u8 as *const c_char,
$source as *const u8 as *const c_char,
$package as *const u8 as *const c_char,
$origin as *const u8 as *const c_char,
))
}
}
unsafe extern "C" fn plugin_init_trampoline(plugin: *mut $crate::ffi::GstPlugin) -> $crate::glib_ffi::gboolean {
use std::panic::{self, AssertUnwindSafe};
let panic_result = panic::catch_unwind(AssertUnwindSafe(|| super::$plugin_init(&from_glib_borrow(plugin))));
match panic_result {
Ok(register_result) => match register_result {
Ok(_) => $crate::glib_ffi::GTRUE,
Err(err) => {
let cat = $crate::DebugCategory::get("GST_PLUGIN_LOADING").unwrap();
gst_error!(cat, "Failed to register plugin: {}", err);
$crate::glib_ffi::GFALSE
}
}
Err(err) => {
let cat = $crate::DebugCategory::get("GST_PLUGIN_LOADING").unwrap();
if let Some(cause) = err.downcast_ref::<&str>() {
gst_error!(cat, "Failed to initialize plugin due to panic: {}", cause);
} else if let Some(cause) = err.downcast_ref::<String>() {
gst_error!(cat, "Failed to initialize plugin due to panic: {}", cause);
} else {
gst_error!(cat, "Failed to initialize plugin due to panic");
}
$crate::glib_ffi::GFALSE
}
}
}
}
pub use plugin_desc::plugin_register_static;
};
);
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment