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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
// Take a look at the license at the top of the repository in the LICENSE file.

use std::{
    marker::PhantomData,
    mem, ops,
    ops::{Deref, DerefMut},
    ptr,
};

use glib::{prelude::*, translate::*};

use crate::{ffi, AllocationParams, Allocator, BufferPool, Structure, StructureRef};

#[derive(Debug, Clone, PartialEq, Eq)]
#[repr(transparent)]
pub struct BufferPoolConfig(Structure);

impl Deref for BufferPoolConfig {
    type Target = BufferPoolConfigRef;

    #[inline]
    fn deref(&self) -> &BufferPoolConfigRef {
        unsafe { &*(self.0.as_ptr() as *const StructureRef as *const BufferPoolConfigRef) }
    }
}

impl DerefMut for BufferPoolConfig {
    #[inline]
    fn deref_mut(&mut self) -> &mut BufferPoolConfigRef {
        unsafe { &mut *(self.0.as_ptr() as *mut StructureRef as *mut BufferPoolConfigRef) }
    }
}

impl AsRef<BufferPoolConfigRef> for BufferPoolConfig {
    #[inline]
    fn as_ref(&self) -> &BufferPoolConfigRef {
        self.deref()
    }
}

impl AsMut<BufferPoolConfigRef> for BufferPoolConfig {
    #[inline]
    fn as_mut(&mut self) -> &mut BufferPoolConfigRef {
        self.deref_mut()
    }
}

#[derive(Debug)]
#[repr(transparent)]
pub struct BufferPoolConfigRef(StructureRef);

impl BufferPoolConfigRef {
    #[inline]
    pub unsafe fn from_glib_borrow<'a>(ptr: *const ffi::GstStructure) -> &'a BufferPoolConfigRef {
        debug_assert!(!ptr.is_null());

        &*(ptr as *mut StructureRef as *mut BufferPoolConfigRef)
    }

    #[inline]
    pub unsafe fn from_glib_borrow_mut<'a>(
        ptr: *mut ffi::GstStructure,
    ) -> &'a mut BufferPoolConfigRef {
        debug_assert!(!ptr.is_null());

        &mut *(ptr as *mut StructureRef as *mut BufferPoolConfigRef)
    }

    #[inline]
    pub fn as_ptr(&self) -> *const ffi::GstStructure {
        self as *const Self as *const ffi::GstStructure
    }

    #[inline]
    pub fn as_mut_ptr(&self) -> *mut ffi::GstStructure {
        self as *const Self as *mut ffi::GstStructure
    }
}

impl ops::Deref for BufferPoolConfigRef {
    type Target = crate::StructureRef;

    #[inline]
    fn deref(&self) -> &crate::StructureRef {
        &self.0
    }
}

impl ops::DerefMut for BufferPoolConfigRef {
    #[inline]
    fn deref_mut(&mut self) -> &mut crate::StructureRef {
        &mut self.0
    }
}

impl AsRef<crate::StructureRef> for BufferPoolConfigRef {
    #[inline]
    fn as_ref(&self) -> &crate::StructureRef {
        &self.0
    }
}

impl AsMut<crate::StructureRef> for BufferPoolConfigRef {
    #[inline]
    fn as_mut(&mut self) -> &mut crate::StructureRef {
        &mut self.0
    }
}

impl BufferPoolConfigRef {
    #[doc(alias = "gst_buffer_pool_config_add_option")]
    pub fn add_option(&mut self, option: &str) {
        unsafe {
            ffi::gst_buffer_pool_config_add_option(self.0.as_mut_ptr(), option.to_glib_none().0);
        }
    }

    #[doc(alias = "gst_buffer_pool_config_has_option")]
    pub fn has_option(&self, option: &str) -> bool {
        unsafe {
            from_glib(ffi::gst_buffer_pool_config_has_option(
                self.0.as_mut_ptr(),
                option.to_glib_none().0,
            ))
        }
    }

    #[doc(alias = "get_options")]
    #[doc(alias = "gst_buffer_pool_config_n_options")]
    #[doc(alias = "gst_buffer_pool_config_get_option")]
    pub fn options(&self) -> Vec<String> {
        unsafe {
            let n = ffi::gst_buffer_pool_config_n_options(self.0.as_mut_ptr()) as usize;
            let mut options = Vec::with_capacity(n);

            for i in 0..n {
                options.push(from_glib_none(ffi::gst_buffer_pool_config_get_option(
                    self.0.as_mut_ptr(),
                    i as u32,
                )));
            }

            options
        }
    }

    #[doc(alias = "gst_buffer_pool_config_set_params")]
    pub fn set_params(
        &mut self,
        caps: Option<&crate::Caps>,
        size: u32,
        min_buffers: u32,
        max_buffers: u32,
    ) {
        unsafe {
            ffi::gst_buffer_pool_config_set_params(
                self.0.as_mut_ptr(),
                caps.to_glib_none().0,
                size,
                min_buffers,
                max_buffers,
            );
        }
    }

    #[doc(alias = "get_params")]
    #[doc(alias = "gst_buffer_pool_config_get_params")]
    pub fn params(&self) -> Option<(Option<crate::Caps>, u32, u32, u32)> {
        unsafe {
            let mut caps = ptr::null_mut();
            let mut size = mem::MaybeUninit::uninit();
            let mut min_buffers = mem::MaybeUninit::uninit();
            let mut max_buffers = mem::MaybeUninit::uninit();

            let ret: bool = from_glib(ffi::gst_buffer_pool_config_get_params(
                self.0.as_mut_ptr(),
                &mut caps,
                size.as_mut_ptr(),
                min_buffers.as_mut_ptr(),
                max_buffers.as_mut_ptr(),
            ));
            if !ret {
                return None;
            }

            Some((
                from_glib_none(caps),
                size.assume_init(),
                min_buffers.assume_init(),
                max_buffers.assume_init(),
            ))
        }
    }

    #[doc(alias = "gst_buffer_pool_config_validate_params")]
    pub fn validate_params(
        &self,
        caps: Option<&crate::Caps>,
        size: u32,
        min_buffers: u32,
        max_buffers: u32,
    ) -> Result<(), glib::BoolError> {
        unsafe {
            glib::result_from_gboolean!(
                ffi::gst_buffer_pool_config_validate_params(
                    self.0.as_mut_ptr(),
                    caps.to_glib_none().0,
                    size,
                    min_buffers,
                    max_buffers,
                ),
                "Parameters are not valid in this context"
            )
        }
    }

    #[doc(alias = "get_allocator")]
    #[doc(alias = "gst_buffer_pool_config_get_allocator")]
    pub fn allocator(&self) -> Option<(Option<Allocator>, AllocationParams)> {
        unsafe {
            let mut allocator = ptr::null_mut();
            let mut params = mem::MaybeUninit::uninit();
            let ret = from_glib(ffi::gst_buffer_pool_config_get_allocator(
                self.0.as_mut_ptr(),
                &mut allocator,
                params.as_mut_ptr(),
            ));
            if ret {
                Some((from_glib_none(allocator), params.assume_init().into()))
            } else {
                None
            }
        }
    }

    #[doc(alias = "gst_buffer_pool_config_set_allocator")]
    pub fn set_allocator(&self, allocator: Option<&Allocator>, params: Option<&AllocationParams>) {
        assert!(allocator.is_some() || params.is_some());
        unsafe {
            ffi::gst_buffer_pool_config_set_allocator(
                self.0.as_mut_ptr(),
                allocator.to_glib_none().0,
                match params {
                    Some(val) => val.as_ptr(),
                    None => ptr::null(),
                },
            )
        }
    }
    // TODO: options iterator
}

#[derive(Debug)]
#[doc(alias = "GstBufferPoolAcquireParams")]
pub struct BufferPoolAcquireParams(ffi::GstBufferPoolAcquireParams);

unsafe impl Send for BufferPoolAcquireParams {}
unsafe impl Sync for BufferPoolAcquireParams {}

impl BufferPoolAcquireParams {
    pub fn with_flags(flags: crate::BufferPoolAcquireFlags) -> Self {
        skip_assert_initialized!();
        BufferPoolAcquireParams(ffi::GstBufferPoolAcquireParams {
            format: ffi::GST_FORMAT_UNDEFINED,
            start: -1,
            stop: -1,
            flags: flags.into_glib(),
            _gst_reserved: [ptr::null_mut(); 4],
        })
    }

    pub fn with_start_stop<T: crate::format::SpecificFormattedValue>(
        start: T,
        stop: T,
        flags: crate::BufferPoolAcquireFlags,
    ) -> Self {
        skip_assert_initialized!();
        unsafe {
            BufferPoolAcquireParams(ffi::GstBufferPoolAcquireParams {
                format: start.format().into_glib(),
                start: start.into_raw_value(),
                stop: stop.into_raw_value(),
                flags: flags.into_glib(),
                _gst_reserved: [ptr::null_mut(); 4],
            })
        }
    }

    pub fn flags(&self) -> crate::BufferPoolAcquireFlags {
        unsafe { from_glib(self.0.flags) }
    }

    pub fn format(&self) -> crate::Format {
        unsafe { from_glib(self.0.format) }
    }

    pub fn start(&self) -> crate::GenericFormattedValue {
        unsafe { crate::GenericFormattedValue::new(from_glib(self.0.format), self.0.start) }
    }

    pub fn stop(&self) -> crate::GenericFormattedValue {
        unsafe { crate::GenericFormattedValue::new(from_glib(self.0.format), self.0.stop) }
    }
}

impl PartialEq for BufferPoolAcquireParams {
    fn eq(&self, other: &Self) -> bool {
        self.format() == other.format()
            && self.start() == other.start()
            && self.stop() == other.stop()
    }
}

impl Eq for BufferPoolAcquireParams {}

#[doc(hidden)]
impl<'a> ToGlibPtr<'a, *const ffi::GstBufferPoolAcquireParams> for BufferPoolAcquireParams {
    type Storage = PhantomData<&'a Self>;

    #[inline]
    fn to_glib_none(
        &'a self,
    ) -> glib::translate::Stash<'a, *const ffi::GstBufferPoolAcquireParams, Self> {
        glib::translate::Stash(&self.0, PhantomData)
    }
}

#[doc(hidden)]
impl<'a> ToGlibPtrMut<'a, *mut ffi::GstBufferPoolAcquireParams> for BufferPoolAcquireParams {
    type Storage = PhantomData<&'a mut Self>;

    #[inline]
    fn to_glib_none_mut(
        &'a mut self,
    ) -> glib::translate::StashMut<'a, *mut ffi::GstBufferPoolAcquireParams, Self> {
        glib::translate::StashMut(&mut self.0, PhantomData)
    }
}

#[doc(hidden)]
impl FromGlibPtrNone<*mut ffi::GstBufferPoolAcquireParams> for BufferPoolAcquireParams {
    #[inline]
    unsafe fn from_glib_none(ptr: *mut ffi::GstBufferPoolAcquireParams) -> Self {
        Self(*ptr)
    }
}

mod sealed {
    pub trait Sealed {}
    impl<T: super::IsA<super::BufferPool>> Sealed for T {}
}

pub trait BufferPoolExtManual: sealed::Sealed + IsA<BufferPool> + 'static {
    /// Gets a copy of the current configuration of the pool. This configuration
    /// can be modified and used for the [`set_config()`][Self::set_config()] call.
    ///
    /// # Returns
    ///
    /// a copy of the current configuration of `self`.
    #[doc(alias = "get_config")]
    #[doc(alias = "gst_buffer_pool_get_config")]
    fn config(&self) -> BufferPoolConfig {
        unsafe {
            let ptr = ffi::gst_buffer_pool_get_config(self.as_ref().to_glib_none().0);
            BufferPoolConfig(from_glib_full(ptr))
        }
    }

    /// Sets the configuration of the pool. If the pool is already configured, and
    /// the configuration hasn't changed, this function will return [`true`]. If the
    /// pool is active, this method will return [`false`] and active configuration
    /// will remain. Buffers allocated from this pool must be returned or else this
    /// function will do nothing and return [`false`].
    ///
    /// `config` is a [`Structure`][crate::Structure] that contains the configuration parameters for
    /// the pool. A default and mandatory set of parameters can be configured with
    /// `gst_buffer_pool_config_set_params()`, `gst_buffer_pool_config_set_allocator()`
    /// and `gst_buffer_pool_config_add_option()`.
    ///
    /// If the parameters in `config` can not be set exactly, this function returns
    /// [`false`] and will try to update as much state as possible. The new state can
    /// then be retrieved and refined with [`config()`][Self::config()].
    ///
    /// This function takes ownership of `config`.
    /// ## `config`
    /// a [`Structure`][crate::Structure]
    ///
    /// # Returns
    ///
    /// [`true`] when the configuration could be set.
    #[doc(alias = "gst_buffer_pool_set_config")]
    fn set_config(&self, config: BufferPoolConfig) -> Result<(), glib::error::BoolError> {
        unsafe {
            glib::result_from_gboolean!(
                ffi::gst_buffer_pool_set_config(
                    self.as_ref().to_glib_none().0,
                    config.0.into_glib_ptr()
                ),
                "Failed to set config",
            )
        }
    }

    fn is_flushing(&self) -> bool {
        unsafe {
            let stash = self.as_ref().to_glib_none();
            let ptr: *mut ffi::GstBufferPool = stash.0;

            from_glib((*ptr).flushing)
        }
    }

    /// Acquires a buffer from `self`. `buffer` should point to a memory location that
    /// can hold a pointer to the new buffer. When the pool is empty, this function
    /// will by default block until a buffer is released into the pool again or when
    /// the pool is set to flushing or deactivated.
    ///
    /// `params` can contain optional parameters to influence the allocation.
    /// ## `params`
    /// parameters.
    ///
    /// # Returns
    ///
    /// a [`FlowReturn`][crate::FlowReturn] such as [`FlowReturn::Flushing`][crate::FlowReturn::Flushing] when the pool is
    /// inactive.
    ///
    /// ## `buffer`
    /// a location for a [`Buffer`][crate::Buffer]
    #[doc(alias = "gst_buffer_pool_acquire_buffer")]
    fn acquire_buffer(
        &self,
        params: Option<&BufferPoolAcquireParams>,
    ) -> Result<crate::Buffer, crate::FlowError> {
        let params_ptr = params.to_glib_none().0 as *mut _;

        unsafe {
            let mut buffer = ptr::null_mut();
            crate::FlowSuccess::try_from_glib(ffi::gst_buffer_pool_acquire_buffer(
                self.as_ref().to_glib_none().0,
                &mut buffer,
                params_ptr,
            ))
            .map(|_| from_glib_full(buffer))
        }
    }
}

impl<O: IsA<BufferPool>> BufferPoolExtManual for O {}

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

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

        let pool = crate::BufferPool::new();
        let mut config = pool.config();
        config.set_params(Some(&crate::Caps::builder("foo/bar").build()), 1024, 0, 2);
        pool.set_config(config).unwrap();

        pool.set_active(true).unwrap();

        let params =
            crate::BufferPoolAcquireParams::with_flags(crate::BufferPoolAcquireFlags::DONTWAIT);

        let _buf1 = pool.acquire_buffer(Some(&params)).unwrap();
        let buf2 = pool.acquire_buffer(Some(&params)).unwrap();

        assert!(pool.acquire_buffer(Some(&params)).is_err());

        drop(buf2);
        let _buf2 = pool.acquire_buffer(Some(&params)).unwrap();

        pool.set_active(false).unwrap();
    }

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

        let pool = crate::BufferPool::new();
        let mut config = pool.config();
        config.set_params(None, 1024, 0, 2);
        pool.set_config(config).unwrap();

        pool.set_active(true).unwrap();
        let _buf1 = pool.acquire_buffer(None).unwrap();
        pool.set_active(false).unwrap();
    }
}