1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
// Take a look at the license at the top of the repository in the LICENSE file.

use crate::auto::functions::parse_bin_from_description;
use glib::prelude::*;
use glib::translate::*;
use std::ptr;

use crate::Bin;
use crate::Element;
use crate::Object;
use crate::ParseContext;
use crate::ParseFlags;

pub fn parse_bin_from_description_with_name(
    bin_description: &str,
    ghost_unlinked_pads: bool,
    bin_name: &str,
) -> Result<Bin, glib::Error> {
    assert_initialized_main_thread!();
    let bin = parse_bin_from_description(bin_description, ghost_unlinked_pads)?;
    if !bin_name.is_empty() {
        let obj = bin.clone().upcast::<Object>();
        unsafe {
            ffi::gst_object_set_name(obj.to_glib_none().0, bin_name.to_glib_none().0);
        }
    }
    Ok(bin)
}

/// This is a convenience wrapper around [`parse_launch()`][crate::parse_launch()] to create a
/// [`Bin`][crate::Bin] from a gst-launch-style pipeline description. See
/// [`parse_launch()`][crate::parse_launch()] and the gst-launch man page for details about the
/// syntax. Ghost pads on the bin for unlinked source or sink pads
/// within the bin can automatically be created (but only a maximum of
/// one ghost pad for each direction will be created; if you expect
/// multiple unlinked source pads or multiple unlinked sink pads
/// and want them all ghosted, you will have to create the ghost pads
/// yourself).
/// ## `bin_description`
/// command line describing the bin
/// ## `ghost_unlinked_pads`
/// whether to automatically create ghost pads
///  for unlinked source or sink pads within the bin
/// ## `context`
/// a parse context allocated with
///  [`ParseContext::new()`][crate::ParseContext::new()], or [`None`]
/// ## `flags`
/// parsing options, or `GST_PARSE_FLAG_NONE`
///
/// # Returns
///
/// a newly-created
///  element, which is guaranteed to be a bin unless
///  [`ParseFlags::NO_SINGLE_ELEMENT_BINS`][crate::ParseFlags::NO_SINGLE_ELEMENT_BINS] was passed, or [`None`] if an error
///  occurred.
#[doc(alias = "gst_parse_bin_from_description_full")]
pub fn parse_bin_from_description_full(
    bin_description: &str,
    ghost_unlinked_pads: bool,
    mut context: Option<&mut ParseContext>,
    flags: ParseFlags,
) -> Result<Element, glib::Error> {
    assert_initialized_main_thread!();
    unsafe {
        let mut error = ptr::null_mut();
        let ret = ffi::gst_parse_bin_from_description_full(
            bin_description.to_glib_none().0,
            ghost_unlinked_pads.into_glib(),
            context.to_glib_none_mut().0,
            flags.into_glib(),
            &mut error,
        );
        if error.is_null() {
            Ok(from_glib_none(ret))
        } else {
            Err(from_glib_full(error))
        }
    }
}

pub fn parse_bin_from_description_with_name_full(
    bin_description: &str,
    ghost_unlinked_pads: bool,
    bin_name: &str,
    context: Option<&mut ParseContext>,
    flags: ParseFlags,
) -> Result<Element, glib::Error> {
    assert_initialized_main_thread!();
    let bin =
        parse_bin_from_description_full(bin_description, ghost_unlinked_pads, context, flags)?;
    if !bin_name.is_empty() {
        let obj = bin.clone().upcast::<Object>();
        unsafe {
            ffi::gst_object_set_name(obj.to_glib_none().0, bin_name.to_glib_none().0);
        }
    }
    Ok(bin)
}

/// Create a new pipeline based on command line syntax.
/// Please note that you might get a return value that is not [`None`] even though
/// the `error` is set. In this case there was a recoverable parsing error and you
/// can try to play the pipeline.
///
/// To create a sub-pipeline (bin) for embedding into an existing pipeline
/// use `gst_parse_bin_from_description_full()`.
/// ## `pipeline_description`
/// the command line describing the pipeline
/// ## `context`
/// a parse context allocated with
///  [`ParseContext::new()`][crate::ParseContext::new()], or [`None`]
/// ## `flags`
/// parsing options, or `GST_PARSE_FLAG_NONE`
///
/// # Returns
///
/// a new element on success, [`None`] on
///  failure. If more than one toplevel element is specified by the
///  `pipeline_description`, all elements are put into a [`Pipeline`][crate::Pipeline], which
///  then is returned (unless the GST_PARSE_FLAG_PLACE_IN_BIN flag is set, in
///  which case they are put in a [`Bin`][crate::Bin] instead).
#[doc(alias = "gst_parse_launch_full")]
pub fn parse_launch_full(
    pipeline_description: &str,
    mut context: Option<&mut ParseContext>,
    flags: ParseFlags,
) -> Result<Element, glib::Error> {
    assert_initialized_main_thread!();
    unsafe {
        let mut error = ptr::null_mut();
        let ret = ffi::gst_parse_launch_full(
            pipeline_description.to_glib_none().0,
            context.to_glib_none_mut().0,
            flags.into_glib(),
            &mut error,
        );
        if error.is_null() {
            Ok(from_glib_none(ret))
        } else {
            Err(from_glib_full(error))
        }
    }
}

/// Create a new element based on command line syntax.
/// `error` will contain an error message if an erroneous pipeline is specified.
/// An error does not mean that the pipeline could not be constructed.
/// ## `argv`
/// null-terminated array of arguments
/// ## `context`
/// a parse context allocated with
///  [`ParseContext::new()`][crate::ParseContext::new()], or [`None`]
/// ## `flags`
/// parsing options, or `GST_PARSE_FLAG_NONE`
///
/// # Returns
///
/// a new element on success; on
///  failure, either [`None`] or a partially-constructed bin or element will be
///  returned and `error` will be set (unless you passed
///  [`ParseFlags::FATAL_ERRORS`][crate::ParseFlags::FATAL_ERRORS] in `flags`, then [`None`] will always be returned
///  on failure)
#[doc(alias = "gst_parse_launchv_full")]
pub fn parse_launchv_full(
    argv: &[&str],
    mut context: Option<&mut ParseContext>,
    flags: ParseFlags,
) -> Result<Element, glib::Error> {
    assert_initialized_main_thread!();
    unsafe {
        let mut error = ptr::null_mut();
        let ret = ffi::gst_parse_launchv_full(
            argv.to_glib_none().0,
            context.to_glib_none_mut().0,
            flags.into_glib(),
            &mut error,
        );
        if error.is_null() {
            Ok(from_glib_none(ret))
        } else {
            Err(from_glib_full(error))
        }
    }
}

/// Calculates the linear regression of the values `xy` and places the
/// result in `m_num`, `m_denom`, `b` and `xbase`, representing the function
///  y(x) = m_num/m_denom * (x - xbase) + b
/// that has the least-square distance from all points `x` and `y`.
///
/// `r_squared` will contain the remaining error.
///
/// If `temp` is not [`None`], it will be used as temporary space for the function,
/// in which case the function works without any allocation at all. If `temp` is
/// [`None`], an allocation will take place. `temp` should have at least the same
/// amount of memory allocated as `xy`, i.e. 2*n*sizeof(GstClockTime).
///
/// > This function assumes (x,y) values with reasonable large differences
/// > between them. It will not calculate the exact results if the differences
/// > between neighbouring values are too small due to not being able to
/// > represent sub-integer values during the calculations.
/// ## `xy`
/// Pairs of (x,y) values
/// ## `temp`
/// Temporary scratch space used by the function
/// ## `n`
/// number of (x,y) pairs
///
/// # Returns
///
/// [`true`] if the linear regression was successfully calculated
///
/// ## `m_num`
/// numerator of calculated slope
///
/// ## `m_denom`
/// denominator of calculated slope
///
/// ## `b`
/// Offset at Y-axis
///
/// ## `xbase`
/// Offset at X-axis
///
/// ## `r_squared`
/// R-squared
#[cfg(any(feature = "v1_12", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v1_12")))]
#[doc(alias = "gst_calculate_linear_regression")]
pub fn calculate_linear_regression(
    xy: &[(u64, u64)],
    temp: Option<&mut [(u64, u64)]>,
) -> Option<(u64, u64, u64, u64, f64)> {
    skip_assert_initialized!();
    use std::mem;

    unsafe {
        assert_eq!(mem::size_of::<u64>() * 2, mem::size_of::<(u64, u64)>());
        assert_eq!(mem::align_of::<u64>(), mem::align_of::<(u64, u64)>());
        assert!(
            temp.as_ref()
                .map(|temp| temp.len())
                .unwrap_or_else(|| xy.len())
                >= xy.len()
        );

        let mut m_num = mem::MaybeUninit::uninit();
        let mut m_denom = mem::MaybeUninit::uninit();
        let mut b = mem::MaybeUninit::uninit();
        let mut xbase = mem::MaybeUninit::uninit();
        let mut r_squared = mem::MaybeUninit::uninit();

        let res = from_glib(ffi::gst_calculate_linear_regression(
            xy.as_ptr() as *const u64,
            temp.map(|temp| temp.as_mut_ptr() as *mut u64)
                .unwrap_or(ptr::null_mut()),
            xy.len() as u32,
            m_num.as_mut_ptr(),
            m_denom.as_mut_ptr(),
            b.as_mut_ptr(),
            xbase.as_mut_ptr(),
            r_squared.as_mut_ptr(),
        ));
        if res {
            Some((
                m_num.assume_init(),
                m_denom.assume_init(),
                b.assume_init(),
                xbase.assume_init(),
                r_squared.assume_init(),
            ))
        } else {
            None
        }
    }
}

/// Checks if `type_` is plugin API. See [`type_mark_as_plugin_api()`][crate::type_mark_as_plugin_api()] for
/// details.
/// ## `type_`
/// a GType
///
/// # Returns
///
/// [`true`] if `type_` is plugin API or [`false`] otherwise.
///
/// ## `flags`
/// What [`PluginAPIFlags`][crate::PluginAPIFlags] the plugin was marked with
#[cfg(any(feature = "v1_18", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v1_18")))]
#[doc(alias = "gst_type_is_plugin_api")]
pub fn type_is_plugin_api(type_: glib::types::Type) -> Option<crate::PluginAPIFlags> {
    assert_initialized_main_thread!();
    unsafe {
        use std::mem;

        let mut flags = mem::MaybeUninit::uninit();
        let ret = from_glib(ffi::gst_type_is_plugin_api(
            type_.into_glib(),
            flags.as_mut_ptr(),
        ));
        let flags = flags.assume_init();
        if ret {
            Some(from_glib(flags))
        } else {
            None
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::prelude::*;

    #[cfg(feature = "v1_12")]
    #[test]
    fn test_calculate_linear_regression() {
        crate::init().unwrap();

        let values = [(0, 0), (1, 1), (2, 2), (3, 3)];

        let (m_num, m_denom, b, xbase, _) = calculate_linear_regression(&values, None).unwrap();
        assert_eq!((m_num, m_denom, b, xbase), (10, 10, 3, 3));

        let mut temp = [(0, 0); 4];
        let (m_num, m_denom, b, xbase, _) =
            calculate_linear_regression(&values, Some(&mut temp)).unwrap();
        assert_eq!((m_num, m_denom, b, xbase), (10, 10, 3, 3));
    }

    #[test]
    fn test_parse_bin_from_description_with_name() {
        crate::init().unwrap();

        let bin =
            parse_bin_from_description_with_name("fakesrc ! fakesink", false, "all_fake").unwrap();
        let name = bin.name();
        assert_eq!(name, "all_fake");

        let bin = parse_bin_from_description_with_name("fakesrc ! fakesink", false, "").unwrap();
        let name = bin.name();
        assert_ne!(name, "");
    }
}