gstreamer/
buffer_pool.rs

1// Take a look at the license at the top of the repository in the LICENSE file.
2
3use std::{
4    marker::PhantomData,
5    mem, ops,
6    ops::{Deref, DerefMut},
7    ptr,
8};
9
10use glib::{prelude::*, translate::*};
11
12use crate::{ffi, AllocationParams, Allocator, BufferPool, Structure, StructureRef};
13
14#[derive(Debug, Clone, PartialEq, Eq)]
15#[repr(transparent)]
16pub struct BufferPoolConfig(Structure);
17
18impl Deref for BufferPoolConfig {
19    type Target = BufferPoolConfigRef;
20
21    #[inline]
22    fn deref(&self) -> &BufferPoolConfigRef {
23        unsafe { &*(self.0.as_ptr() as *const StructureRef as *const BufferPoolConfigRef) }
24    }
25}
26
27impl DerefMut for BufferPoolConfig {
28    #[inline]
29    fn deref_mut(&mut self) -> &mut BufferPoolConfigRef {
30        unsafe { &mut *(self.0.as_ptr() as *mut StructureRef as *mut BufferPoolConfigRef) }
31    }
32}
33
34impl AsRef<BufferPoolConfigRef> for BufferPoolConfig {
35    #[inline]
36    fn as_ref(&self) -> &BufferPoolConfigRef {
37        self.deref()
38    }
39}
40
41impl AsMut<BufferPoolConfigRef> for BufferPoolConfig {
42    #[inline]
43    fn as_mut(&mut self) -> &mut BufferPoolConfigRef {
44        self.deref_mut()
45    }
46}
47
48#[derive(Debug)]
49#[repr(transparent)]
50pub struct BufferPoolConfigRef(StructureRef);
51
52impl BufferPoolConfigRef {
53    #[inline]
54    pub unsafe fn from_glib_borrow<'a>(ptr: *const ffi::GstStructure) -> &'a BufferPoolConfigRef {
55        debug_assert!(!ptr.is_null());
56
57        &*(ptr as *mut StructureRef as *mut BufferPoolConfigRef)
58    }
59
60    #[inline]
61    pub unsafe fn from_glib_borrow_mut<'a>(
62        ptr: *mut ffi::GstStructure,
63    ) -> &'a mut BufferPoolConfigRef {
64        debug_assert!(!ptr.is_null());
65
66        &mut *(ptr as *mut StructureRef as *mut BufferPoolConfigRef)
67    }
68
69    #[inline]
70    pub fn as_ptr(&self) -> *const ffi::GstStructure {
71        self as *const Self as *const ffi::GstStructure
72    }
73
74    #[inline]
75    pub fn as_mut_ptr(&self) -> *mut ffi::GstStructure {
76        self as *const Self as *mut ffi::GstStructure
77    }
78}
79
80impl ops::Deref for BufferPoolConfigRef {
81    type Target = crate::StructureRef;
82
83    #[inline]
84    fn deref(&self) -> &crate::StructureRef {
85        &self.0
86    }
87}
88
89impl ops::DerefMut for BufferPoolConfigRef {
90    #[inline]
91    fn deref_mut(&mut self) -> &mut crate::StructureRef {
92        &mut self.0
93    }
94}
95
96impl AsRef<crate::StructureRef> for BufferPoolConfigRef {
97    #[inline]
98    fn as_ref(&self) -> &crate::StructureRef {
99        &self.0
100    }
101}
102
103impl AsMut<crate::StructureRef> for BufferPoolConfigRef {
104    #[inline]
105    fn as_mut(&mut self) -> &mut crate::StructureRef {
106        &mut self.0
107    }
108}
109
110impl BufferPoolConfigRef {
111    #[doc(alias = "gst_buffer_pool_config_add_option")]
112    pub fn add_option(&mut self, option: &str) {
113        unsafe {
114            ffi::gst_buffer_pool_config_add_option(self.0.as_mut_ptr(), option.to_glib_none().0);
115        }
116    }
117
118    #[doc(alias = "gst_buffer_pool_config_has_option")]
119    pub fn has_option(&self, option: &str) -> bool {
120        unsafe {
121            from_glib(ffi::gst_buffer_pool_config_has_option(
122                self.0.as_mut_ptr(),
123                option.to_glib_none().0,
124            ))
125        }
126    }
127
128    #[doc(alias = "get_options")]
129    #[doc(alias = "gst_buffer_pool_config_n_options")]
130    #[doc(alias = "gst_buffer_pool_config_get_option")]
131    pub fn options(&self) -> OptionsIter<'_> {
132        OptionsIter::new(self)
133    }
134
135    #[doc(alias = "gst_buffer_pool_config_set_params")]
136    pub fn set_params(
137        &mut self,
138        caps: Option<&crate::Caps>,
139        size: u32,
140        min_buffers: u32,
141        max_buffers: u32,
142    ) {
143        unsafe {
144            ffi::gst_buffer_pool_config_set_params(
145                self.0.as_mut_ptr(),
146                caps.to_glib_none().0,
147                size,
148                min_buffers,
149                max_buffers,
150            );
151        }
152    }
153
154    #[doc(alias = "get_params")]
155    #[doc(alias = "gst_buffer_pool_config_get_params")]
156    pub fn params(&self) -> Option<(Option<crate::Caps>, u32, u32, u32)> {
157        unsafe {
158            let mut caps = ptr::null_mut();
159            let mut size = mem::MaybeUninit::uninit();
160            let mut min_buffers = mem::MaybeUninit::uninit();
161            let mut max_buffers = mem::MaybeUninit::uninit();
162
163            let ret: bool = from_glib(ffi::gst_buffer_pool_config_get_params(
164                self.0.as_mut_ptr(),
165                &mut caps,
166                size.as_mut_ptr(),
167                min_buffers.as_mut_ptr(),
168                max_buffers.as_mut_ptr(),
169            ));
170            if !ret {
171                return None;
172            }
173
174            Some((
175                from_glib_none(caps),
176                size.assume_init(),
177                min_buffers.assume_init(),
178                max_buffers.assume_init(),
179            ))
180        }
181    }
182
183    #[doc(alias = "gst_buffer_pool_config_validate_params")]
184    pub fn validate_params(
185        &self,
186        caps: Option<&crate::Caps>,
187        size: u32,
188        min_buffers: u32,
189        max_buffers: u32,
190    ) -> Result<(), glib::BoolError> {
191        unsafe {
192            glib::result_from_gboolean!(
193                ffi::gst_buffer_pool_config_validate_params(
194                    self.0.as_mut_ptr(),
195                    caps.to_glib_none().0,
196                    size,
197                    min_buffers,
198                    max_buffers,
199                ),
200                "Parameters are not valid in this context"
201            )
202        }
203    }
204
205    #[doc(alias = "get_allocator")]
206    #[doc(alias = "gst_buffer_pool_config_get_allocator")]
207    pub fn allocator(&self) -> Option<(Option<Allocator>, AllocationParams)> {
208        unsafe {
209            let mut allocator = ptr::null_mut();
210            let mut params = mem::MaybeUninit::uninit();
211            let ret = from_glib(ffi::gst_buffer_pool_config_get_allocator(
212                self.0.as_mut_ptr(),
213                &mut allocator,
214                params.as_mut_ptr(),
215            ));
216            if ret {
217                Some((from_glib_none(allocator), params.assume_init().into()))
218            } else {
219                None
220            }
221        }
222    }
223
224    #[doc(alias = "gst_buffer_pool_config_set_allocator")]
225    pub fn set_allocator(&self, allocator: Option<&Allocator>, params: Option<&AllocationParams>) {
226        assert!(allocator.is_some() || params.is_some());
227        unsafe {
228            ffi::gst_buffer_pool_config_set_allocator(
229                self.0.as_mut_ptr(),
230                allocator.to_glib_none().0,
231                match params {
232                    Some(val) => val.as_ptr(),
233                    None => ptr::null(),
234                },
235            )
236        }
237    }
238}
239
240crate::utils::define_fixed_size_iter!(
241    OptionsIter,
242    &'a BufferPoolConfigRef,
243    &'a glib::GStr,
244    |collection: &BufferPoolConfigRef| unsafe {
245        ffi::gst_buffer_pool_config_n_options(collection.as_mut_ptr()) as usize
246    },
247    |collection: &BufferPoolConfigRef, idx: usize| unsafe {
248        glib::GStr::from_ptr(ffi::gst_buffer_pool_config_get_option(
249            collection.as_mut_ptr(),
250            idx as u32,
251        ))
252    }
253);
254
255#[derive(Debug, Copy, Clone)]
256#[doc(alias = "GstBufferPoolAcquireParams")]
257pub struct BufferPoolAcquireParams(ffi::GstBufferPoolAcquireParams);
258
259unsafe impl Send for BufferPoolAcquireParams {}
260unsafe impl Sync for BufferPoolAcquireParams {}
261
262impl BufferPoolAcquireParams {
263    pub fn with_flags(flags: crate::BufferPoolAcquireFlags) -> Self {
264        skip_assert_initialized!();
265        BufferPoolAcquireParams(ffi::GstBufferPoolAcquireParams {
266            format: ffi::GST_FORMAT_UNDEFINED,
267            start: -1,
268            stop: -1,
269            flags: flags.into_glib(),
270            _gst_reserved: [ptr::null_mut(); 4],
271        })
272    }
273
274    pub fn with_start_stop<T: crate::format::SpecificFormattedValue>(
275        start: T,
276        stop: T,
277        flags: crate::BufferPoolAcquireFlags,
278    ) -> Self {
279        skip_assert_initialized!();
280        unsafe {
281            BufferPoolAcquireParams(ffi::GstBufferPoolAcquireParams {
282                format: start.format().into_glib(),
283                start: start.into_raw_value(),
284                stop: stop.into_raw_value(),
285                flags: flags.into_glib(),
286                _gst_reserved: [ptr::null_mut(); 4],
287            })
288        }
289    }
290
291    pub fn flags(&self) -> crate::BufferPoolAcquireFlags {
292        unsafe { from_glib(self.0.flags) }
293    }
294
295    pub fn format(&self) -> crate::Format {
296        unsafe { from_glib(self.0.format) }
297    }
298
299    pub fn start(&self) -> crate::GenericFormattedValue {
300        unsafe { crate::GenericFormattedValue::new(from_glib(self.0.format), self.0.start) }
301    }
302
303    pub fn stop(&self) -> crate::GenericFormattedValue {
304        unsafe { crate::GenericFormattedValue::new(from_glib(self.0.format), self.0.stop) }
305    }
306
307    pub fn set_flags(&mut self, flags: crate::BufferPoolAcquireFlags) {
308        self.0.flags = flags.into_glib();
309    }
310
311    pub fn set_format(&mut self, format: crate::Format) {
312        self.0.format = format.into_glib();
313    }
314
315    pub fn set_start(&mut self, start: crate::GenericFormattedValue) {
316        assert_eq!(self.format(), start.format());
317        self.0.start = start.value();
318    }
319
320    pub fn set_stop(&mut self, stop: crate::GenericFormattedValue) {
321        assert_eq!(self.format(), stop.format());
322        self.0.stop = stop.value();
323    }
324}
325
326impl PartialEq for BufferPoolAcquireParams {
327    fn eq(&self, other: &Self) -> bool {
328        self.flags() == other.flags()
329            && self.format() == other.format()
330            && self.start() == other.start()
331            && self.stop() == other.stop()
332    }
333}
334
335impl Eq for BufferPoolAcquireParams {}
336
337impl Default for BufferPoolAcquireParams {
338    fn default() -> Self {
339        Self(ffi::GstBufferPoolAcquireParams {
340            format: ffi::GST_FORMAT_UNDEFINED,
341            start: -1,
342            stop: -1,
343            flags: ffi::GST_BUFFER_POOL_ACQUIRE_FLAG_NONE,
344            _gst_reserved: [ptr::null_mut(); 4],
345        })
346    }
347}
348
349#[doc(hidden)]
350impl<'a> ToGlibPtr<'a, *const ffi::GstBufferPoolAcquireParams> for BufferPoolAcquireParams {
351    type Storage = PhantomData<&'a Self>;
352
353    #[inline]
354    fn to_glib_none(
355        &'a self,
356    ) -> glib::translate::Stash<'a, *const ffi::GstBufferPoolAcquireParams, Self> {
357        glib::translate::Stash(&self.0, PhantomData)
358    }
359}
360
361#[doc(hidden)]
362impl<'a> ToGlibPtrMut<'a, *mut ffi::GstBufferPoolAcquireParams> for BufferPoolAcquireParams {
363    type Storage = PhantomData<&'a mut Self>;
364
365    #[inline]
366    fn to_glib_none_mut(
367        &'a mut self,
368    ) -> glib::translate::StashMut<'a, *mut ffi::GstBufferPoolAcquireParams, Self> {
369        glib::translate::StashMut(&mut self.0, PhantomData)
370    }
371}
372
373#[doc(hidden)]
374impl FromGlibPtrNone<*mut ffi::GstBufferPoolAcquireParams> for BufferPoolAcquireParams {
375    #[inline]
376    unsafe fn from_glib_none(ptr: *mut ffi::GstBufferPoolAcquireParams) -> Self {
377        Self(*ptr)
378    }
379}
380
381pub trait BufferPoolExtManual: IsA<BufferPool> + 'static {
382    /// Gets a copy of the current configuration of the pool. This configuration
383    /// can be modified and used for the [`set_config()`][Self::set_config()] call.
384    ///
385    /// # Returns
386    ///
387    /// a copy of the current configuration of `self`.
388    #[doc(alias = "get_config")]
389    #[doc(alias = "gst_buffer_pool_get_config")]
390    fn config(&self) -> BufferPoolConfig {
391        unsafe {
392            let ptr = ffi::gst_buffer_pool_get_config(self.as_ref().to_glib_none().0);
393            BufferPoolConfig(from_glib_full(ptr))
394        }
395    }
396
397    /// Sets the configuration of the pool. If the pool is already configured, and
398    /// the configuration hasn't changed, this function will return [`true`]. If the
399    /// pool is active, this method will return [`false`] and active configuration
400    /// will remain. Buffers allocated from this pool must be returned or else this
401    /// function will do nothing and return [`false`].
402    ///
403    /// `config` is a [`Structure`][crate::Structure] that contains the configuration parameters for
404    /// the pool. A default and mandatory set of parameters can be configured with
405    /// `gst_buffer_pool_config_set_params()`, `gst_buffer_pool_config_set_allocator()`
406    /// and `gst_buffer_pool_config_add_option()`.
407    ///
408    /// If the parameters in `config` can not be set exactly, this function returns
409    /// [`false`] and will try to update as much state as possible. The new state can
410    /// then be retrieved and refined with [`config()`][Self::config()].
411    ///
412    /// This function takes ownership of `config`.
413    /// ## `config`
414    /// a [`Structure`][crate::Structure]
415    ///
416    /// # Returns
417    ///
418    /// [`true`] when the configuration could be set.
419    #[doc(alias = "gst_buffer_pool_set_config")]
420    fn set_config(&self, config: BufferPoolConfig) -> Result<(), glib::error::BoolError> {
421        unsafe {
422            glib::result_from_gboolean!(
423                ffi::gst_buffer_pool_set_config(
424                    self.as_ref().to_glib_none().0,
425                    config.0.into_glib_ptr()
426                ),
427                "Failed to set config",
428            )
429        }
430    }
431
432    fn is_flushing(&self) -> bool {
433        unsafe {
434            let stash = self.as_ref().to_glib_none();
435            let ptr: *mut ffi::GstBufferPool = stash.0;
436
437            from_glib((*ptr).flushing)
438        }
439    }
440
441    /// Acquires a buffer from `self`. `buffer` should point to a memory location that
442    /// can hold a pointer to the new buffer. When the pool is empty, this function
443    /// will by default block until a buffer is released into the pool again or when
444    /// the pool is set to flushing or deactivated.
445    ///
446    /// `params` can contain optional parameters to influence the allocation.
447    /// ## `params`
448    /// parameters.
449    ///
450    /// # Returns
451    ///
452    /// a [`FlowReturn`][crate::FlowReturn] such as [`FlowReturn::Flushing`][crate::FlowReturn::Flushing] when the pool is
453    /// inactive.
454    ///
455    /// ## `buffer`
456    /// a location for a [`Buffer`][crate::Buffer]
457    #[doc(alias = "gst_buffer_pool_acquire_buffer")]
458    fn acquire_buffer(
459        &self,
460        params: Option<&BufferPoolAcquireParams>,
461    ) -> Result<crate::Buffer, crate::FlowError> {
462        let params_ptr = params.to_glib_none().0 as *mut _;
463
464        unsafe {
465            let mut buffer = ptr::null_mut();
466            crate::FlowSuccess::try_from_glib(ffi::gst_buffer_pool_acquire_buffer(
467                self.as_ref().to_glib_none().0,
468                &mut buffer,
469                params_ptr,
470            ))
471            .map(|_| from_glib_full(buffer))
472        }
473    }
474}
475
476impl<O: IsA<BufferPool>> BufferPoolExtManual for O {}
477
478#[cfg(test)]
479mod tests {
480    use super::*;
481    use crate::prelude::*;
482
483    #[test]
484    fn pool_with_params() {
485        crate::init().unwrap();
486
487        let pool = crate::BufferPool::new();
488        let mut config = pool.config();
489        config.set_params(Some(&crate::Caps::builder("foo/bar").build()), 1024, 0, 2);
490        pool.set_config(config).unwrap();
491
492        pool.set_active(true).unwrap();
493
494        let params =
495            crate::BufferPoolAcquireParams::with_flags(crate::BufferPoolAcquireFlags::DONTWAIT);
496
497        let _buf1 = pool.acquire_buffer(Some(&params)).unwrap();
498        let buf2 = pool.acquire_buffer(Some(&params)).unwrap();
499
500        assert!(pool.acquire_buffer(Some(&params)).is_err());
501
502        drop(buf2);
503        let _buf2 = pool.acquire_buffer(Some(&params)).unwrap();
504
505        pool.set_active(false).unwrap();
506    }
507
508    #[test]
509    fn pool_no_params() {
510        crate::init().unwrap();
511
512        let pool = crate::BufferPool::new();
513        let mut config = pool.config();
514        config.set_params(None, 1024, 0, 2);
515        pool.set_config(config).unwrap();
516
517        pool.set_active(true).unwrap();
518        let _buf1 = pool.acquire_buffer(None).unwrap();
519        pool.set_active(false).unwrap();
520    }
521}