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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
// Take a look at the license at the top of the repository in the LICENSE file.

use std::ptr;

use glib::{
    prelude::*,
    subclass::{prelude::*, InitializingObject},
    translate::*,
};
use libc::c_char;

use super::prelude::*;
use crate::{ffi, BufferPool, BufferPoolAcquireParams, BufferPoolConfigRef};

pub trait BufferPoolImpl: BufferPoolImplExt + GstObjectImpl + Send + Sync {
    /// 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]
    fn acquire_buffer(
        &self,
        params: Option<&BufferPoolAcquireParams>,
    ) -> Result<crate::Buffer, crate::FlowError> {
        self.parent_acquire_buffer(params)
    }

    /// Allocate a buffer. the default implementation allocates
    /// buffers from the configured memory allocator and with the configured
    /// parameters. All metadata that is present on the allocated buffer will
    /// be marked as [`MetaFlags::POOLED`][crate::MetaFlags::POOLED] and [`MetaFlags::LOCKED`][crate::MetaFlags::LOCKED] and will
    /// not be removed from the buffer in `GstBufferPoolClass::reset_buffer`.
    /// The buffer should have the [`BufferFlags::TAG_MEMORY`][crate::BufferFlags::TAG_MEMORY] cleared.
    /// ## `params`
    /// parameters.
    ///
    /// # Returns
    ///
    /// a [`FlowReturn`][crate::FlowReturn] to indicate whether the allocation was
    /// successful.
    ///
    /// ## `buffer`
    /// a location for a [`Buffer`][crate::Buffer]
    fn alloc_buffer(
        &self,
        params: Option<&BufferPoolAcquireParams>,
    ) -> Result<crate::Buffer, crate::FlowError> {
        self.parent_alloc_buffer(params)
    }

    /// Enter the flushing state.
    fn flush_start(&self) {
        self.parent_flush_start()
    }

    /// Leave the flushing state.
    fn flush_stop(&self) {
        self.parent_flush_stop()
    }

    /// Free a buffer. The default implementation unrefs the buffer.
    /// ## `buffer`
    /// the [`Buffer`][crate::Buffer] to free
    fn free_buffer(&self, buffer: crate::Buffer) {
        self.parent_free_buffer(buffer)
    }

    /// Releases `buffer` to `self`. `buffer` should have previously been allocated from
    /// `self` with [`BufferPoolExtManual::acquire_buffer()`][crate::prelude::BufferPoolExtManual::acquire_buffer()].
    ///
    /// This function is usually called automatically when the last ref on `buffer`
    /// disappears.
    /// ## `buffer`
    /// a [`Buffer`][crate::Buffer]
    fn release_buffer(&self, buffer: crate::Buffer) {
        self.parent_release_buffer(buffer)
    }

    /// Reset the buffer to its state when it was freshly allocated.
    /// The default implementation will clear the flags, timestamps and
    /// will remove the metadata without the [`MetaFlags::POOLED`][crate::MetaFlags::POOLED] flag (even
    /// the metadata with [`MetaFlags::LOCKED`][crate::MetaFlags::LOCKED]). If the
    /// [`BufferFlags::TAG_MEMORY`][crate::BufferFlags::TAG_MEMORY] was set, this function can also try to
    /// restore the memory and clear the [`BufferFlags::TAG_MEMORY`][crate::BufferFlags::TAG_MEMORY] again.
    /// ## `buffer`
    /// the [`Buffer`][crate::Buffer] to reset
    fn reset_buffer(&self, buffer: &mut crate::BufferRef) {
        self.parent_reset_buffer(buffer)
    }

    /// Start the bufferpool. The default implementation will preallocate
    /// min-buffers buffers and put them in the queue.
    ///
    /// Subclasses do not need to chain up to the parent's default implementation
    /// if they don't want min-buffers based preallocation.
    ///
    /// # Returns
    ///
    /// whether the pool could be started.
    fn start(&self) -> bool {
        self.parent_start()
    }

    /// Stop the bufferpool. the default implementation will free the
    /// preallocated buffers. This function is called when all the buffers are
    /// returned to the pool.
    ///
    /// # Returns
    ///
    /// whether the pool could be stopped.
    fn stop(&self) -> bool {
        self.parent_stop()
    }

    /// Gets a [`None`] terminated array of string with supported bufferpool options for
    /// `self`. An option would typically be enabled with
    /// `gst_buffer_pool_config_add_option()`.
    ///
    /// # Returns
    ///
    /// a [`None`] terminated array
    ///  of strings.
    fn options() -> &'static [&'static str] {
        &[]
    }

    /// 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 [`BufferPoolExtManual::config()`][crate::prelude::BufferPoolExtManual::config()].
    ///
    /// This function takes ownership of `config`.
    /// ## `config`
    /// a [`Structure`][crate::Structure]
    ///
    /// # Returns
    ///
    /// [`true`] when the configuration could be set.
    fn set_config(&self, config: &mut BufferPoolConfigRef) -> bool {
        self.parent_set_config(config)
    }
}

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

pub trait BufferPoolImplExt: sealed::Sealed + ObjectSubclass {
    fn parent_acquire_buffer(
        &self,
        params: Option<&BufferPoolAcquireParams>,
    ) -> Result<crate::Buffer, crate::FlowError> {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GstBufferPoolClass;
            if let Some(f) = (*parent_class).acquire_buffer {
                let params_ptr = mut_override(params.to_glib_none().0);
                let mut buffer = std::ptr::null_mut();

                let result = f(
                    self.obj()
                        .unsafe_cast_ref::<crate::BufferPool>()
                        .to_glib_none()
                        .0,
                    &mut buffer,
                    params_ptr,
                );

                crate::FlowSuccess::try_from_glib(result).map(|_| from_glib_full(buffer))
            } else {
                Err(crate::FlowError::NotSupported)
            }
        }
    }

    fn parent_alloc_buffer(
        &self,
        params: Option<&BufferPoolAcquireParams>,
    ) -> Result<crate::Buffer, crate::FlowError> {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GstBufferPoolClass;
            if let Some(f) = (*parent_class).alloc_buffer {
                let params_ptr = mut_override(params.to_glib_none().0);
                let mut buffer = std::ptr::null_mut();

                let result = f(
                    self.obj()
                        .unsafe_cast_ref::<crate::BufferPool>()
                        .to_glib_none()
                        .0,
                    &mut buffer,
                    params_ptr,
                );

                crate::FlowSuccess::try_from_glib(result).map(|_| from_glib_full(buffer))
            } else {
                Err(crate::FlowError::NotSupported)
            }
        }
    }

    fn parent_free_buffer(&self, buffer: crate::Buffer) {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GstBufferPoolClass;
            if let Some(f) = (*parent_class).free_buffer {
                f(
                    self.obj()
                        .unsafe_cast_ref::<crate::BufferPool>()
                        .to_glib_none()
                        .0,
                    buffer.into_glib_ptr(),
                )
            }
        }
    }

    fn parent_release_buffer(&self, buffer: crate::Buffer) {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GstBufferPoolClass;
            if let Some(f) = (*parent_class).release_buffer {
                f(
                    self.obj()
                        .unsafe_cast_ref::<crate::BufferPool>()
                        .to_glib_none()
                        .0,
                    buffer.into_glib_ptr(),
                )
            }
        }
    }

    fn parent_reset_buffer(&self, buffer: &mut crate::BufferRef) {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GstBufferPoolClass;
            if let Some(f) = (*parent_class).reset_buffer {
                f(
                    self.obj()
                        .unsafe_cast_ref::<crate::BufferPool>()
                        .to_glib_none()
                        .0,
                    buffer.as_mut_ptr(),
                )
            }
        }
    }

    fn parent_start(&self) -> bool {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GstBufferPoolClass;
            if let Some(f) = (*parent_class).start {
                let result = f(self
                    .obj()
                    .unsafe_cast_ref::<crate::BufferPool>()
                    .to_glib_none()
                    .0);

                from_glib(result)
            } else {
                true
            }
        }
    }

    fn parent_stop(&self) -> bool {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GstBufferPoolClass;
            if let Some(f) = (*parent_class).stop {
                let result = f(self
                    .obj()
                    .unsafe_cast_ref::<crate::BufferPool>()
                    .to_glib_none()
                    .0);

                from_glib(result)
            } else {
                true
            }
        }
    }

    fn parent_set_config(&self, config: &mut BufferPoolConfigRef) -> bool {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GstBufferPoolClass;
            if let Some(f) = (*parent_class).set_config {
                let result = f(
                    self.obj()
                        .unsafe_cast_ref::<crate::BufferPool>()
                        .to_glib_none()
                        .0,
                    (*config).as_mut_ptr(),
                );

                from_glib(result)
            } else {
                false
            }
        }
    }

    fn parent_flush_start(&self) {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GstBufferPoolClass;
            if let Some(f) = (*parent_class).flush_start {
                f(self
                    .obj()
                    .unsafe_cast_ref::<crate::BufferPool>()
                    .to_glib_none()
                    .0)
            }
        }
    }

    fn parent_flush_stop(&self) {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GstBufferPoolClass;
            if let Some(f) = (*parent_class).flush_stop {
                f(self
                    .obj()
                    .unsafe_cast_ref::<crate::BufferPool>()
                    .to_glib_none()
                    .0)
            }
        }
    }
}

impl<T: BufferPoolImpl> BufferPoolImplExt for T {}

unsafe impl<T: BufferPoolImpl> IsSubclassable<T> for BufferPool {
    fn class_init(klass: &mut glib::Class<Self>) {
        Self::parent_class_init::<T>(klass);
        let klass = klass.as_mut();
        klass.acquire_buffer = Some(buffer_pool_acquire_buffer::<T>);
        klass.alloc_buffer = Some(buffer_pool_alloc_buffer::<T>);
        klass.release_buffer = Some(buffer_pool_release_buffer::<T>);
        klass.reset_buffer = Some(buffer_pool_reset_buffer::<T>);
        klass.start = Some(buffer_pool_start::<T>);
        klass.stop = Some(buffer_pool_stop::<T>);
        klass.get_options = Some(buffer_pool_get_options::<T>);
        klass.set_config = Some(buffer_pool_set_config::<T>);
        klass.flush_start = Some(buffer_pool_flush_start::<T>);
        klass.flush_stop = Some(buffer_pool_flush_stop::<T>);
        klass.free_buffer = Some(buffer_pool_free_buffer::<T>);
    }

    fn instance_init(instance: &mut InitializingObject<T>) {
        Self::parent_instance_init(instance);

        // Store the pool options in the instance data
        // for later retrieval in buffer_pool_get_options
        let options = T::options();
        instance.set_instance_data(T::type_(), glib::StrV::from(options));
    }
}

unsafe extern "C" fn buffer_pool_acquire_buffer<T: BufferPoolImpl>(
    ptr: *mut ffi::GstBufferPool,
    buffer: *mut *mut ffi::GstBuffer,
    params: *mut ffi::GstBufferPoolAcquireParams,
) -> ffi::GstFlowReturn {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();
    let params: Option<BufferPoolAcquireParams> = from_glib_none(params);

    match imp.acquire_buffer(params.as_ref()) {
        Ok(b) => {
            *buffer = b.into_glib_ptr();
            ffi::GST_FLOW_OK
        }
        Err(err) => err.into_glib(),
    }
}

unsafe extern "C" fn buffer_pool_alloc_buffer<T: BufferPoolImpl>(
    ptr: *mut ffi::GstBufferPool,
    buffer: *mut *mut ffi::GstBuffer,
    params: *mut ffi::GstBufferPoolAcquireParams,
) -> ffi::GstFlowReturn {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();
    let params: Option<BufferPoolAcquireParams> = from_glib_none(params);

    match imp.alloc_buffer(params.as_ref()) {
        Ok(b) => {
            *buffer = b.into_glib_ptr();
            ffi::GST_FLOW_OK
        }
        Err(err) => err.into_glib(),
    }
}

unsafe extern "C" fn buffer_pool_flush_start<T: BufferPoolImpl>(ptr: *mut ffi::GstBufferPool) {
    // the GstBufferPool implementation calls this
    // in finalize where the ref_count will already
    // be zero and we are actually destroyed
    // see: https://gitlab.freedesktop.org/gstreamer/gstreamer/-/merge_requests/1645
    if (*(ptr as *const glib::gobject_ffi::GObject)).ref_count == 0 {
        // flush_start is a no-op in GstBufferPool
        return;
    }

    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();
    imp.flush_start();
}

unsafe extern "C" fn buffer_pool_flush_stop<T: BufferPoolImpl>(ptr: *mut ffi::GstBufferPool) {
    // the GstBufferPool implementation calls this
    // in finalize where the ref_count will already
    // be zero and we are actually destroyed
    // see: https://gitlab.freedesktop.org/gstreamer/gstreamer/-/merge_requests/1645
    if (*(ptr as *const glib::gobject_ffi::GObject)).ref_count == 0 {
        // flush_stop is a no-op in GstBufferPool
        return;
    }

    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();
    imp.flush_stop();
}

unsafe extern "C" fn buffer_pool_free_buffer<T: BufferPoolImpl>(
    ptr: *mut ffi::GstBufferPool,
    buffer: *mut ffi::GstBuffer,
) {
    // the GstBufferPool implementation calls this
    // in finalize where the ref_count will already
    // be zero and we are actually destroyed
    // see: https://gitlab.freedesktop.org/gstreamer/gstreamer/-/merge_requests/1645
    if (*(ptr as *const glib::gobject_ffi::GObject)).ref_count == 0 {
        // As a workaround we call free_buffer directly on the
        // GstBufferPool to prevent leaking the buffer
        // This will NOT call free_buffer on a subclass.
        let pool_class =
            glib::Class::<crate::BufferPool>::from_type(crate::BufferPool::static_type()).unwrap();
        let pool_class = pool_class.as_ref();
        if let Some(f) = pool_class.free_buffer {
            f(ptr, buffer)
        }
        return;
    }

    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();
    imp.free_buffer(from_glib_full(buffer));
}

unsafe extern "C" fn buffer_pool_release_buffer<T: BufferPoolImpl>(
    ptr: *mut ffi::GstBufferPool,
    buffer: *mut ffi::GstBuffer,
) {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();
    imp.release_buffer(from_glib_full(buffer));
}

unsafe extern "C" fn buffer_pool_reset_buffer<T: BufferPoolImpl>(
    ptr: *mut ffi::GstBufferPool,
    buffer: *mut ffi::GstBuffer,
) {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();
    imp.reset_buffer(crate::BufferRef::from_mut_ptr(buffer));
}

unsafe extern "C" fn buffer_pool_start<T: BufferPoolImpl>(
    ptr: *mut ffi::GstBufferPool,
) -> glib::ffi::gboolean {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();
    imp.start().into_glib()
}

unsafe extern "C" fn buffer_pool_stop<T: BufferPoolImpl>(
    ptr: *mut ffi::GstBufferPool,
) -> glib::ffi::gboolean {
    // the GstBufferPool implementation calls this
    // in finalize where the ref_count will already
    // be zero and we are actually destroyed
    // see: https://gitlab.freedesktop.org/gstreamer/gstreamer/-/merge_requests/1645
    if (*(ptr as *const glib::gobject_ffi::GObject)).ref_count == 0 {
        // As a workaround we call stop directly on the GstBufferPool
        // This is needed because the default implementation clears
        // the pool in stop.
        let pool_class =
            glib::Class::<crate::BufferPool>::from_type(crate::BufferPool::static_type()).unwrap();
        let pool_class = pool_class.as_ref();
        let result = if let Some(f) = pool_class.stop {
            f(ptr)
        } else {
            true.into_glib()
        };

        return result;
    }

    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();
    imp.stop().into_glib()
}

unsafe extern "C" fn buffer_pool_get_options<T: BufferPoolImpl>(
    ptr: *mut ffi::GstBufferPool,
) -> *mut *const c_char {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();
    T::instance_data::<glib::StrV>(imp, T::type_())
        .map(|p| p.as_ptr() as *mut *const _)
        .unwrap_or(ptr::null_mut())
}

unsafe extern "C" fn buffer_pool_set_config<T: BufferPoolImpl>(
    ptr: *mut ffi::GstBufferPool,
    config: *mut ffi::GstStructure,
) -> glib::ffi::gboolean {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();
    imp.set_config(BufferPoolConfigRef::from_glib_borrow_mut(config))
        .into_glib()
}

#[cfg(test)]
mod tests {
    use std::sync::{
        atomic::{AtomicBool, Ordering},
        Arc,
    };

    use super::*;
    use crate::prelude::*;

    pub mod imp {
        use super::*;

        #[derive(Default)]
        pub struct TestBufferPool;

        impl ObjectImpl for TestBufferPool {}
        impl GstObjectImpl for TestBufferPool {}
        impl BufferPoolImpl for TestBufferPool {
            fn options() -> &'static [&'static str] {
                &["TEST_OPTION"]
            }

            fn set_config(&self, config: &mut BufferPoolConfigRef) -> bool {
                let (caps, size, min_buffers, max_buffers) = config.params().unwrap();
                config.set_params(caps.as_ref(), size * 2, min_buffers, max_buffers);
                self.parent_set_config(config)
            }
        }

        #[glib::object_subclass]
        impl ObjectSubclass for TestBufferPool {
            const NAME: &'static str = "TestBufferPool";
            type Type = super::TestBufferPool;
            type ParentType = BufferPool;
        }
    }

    glib::wrapper! {
        pub struct TestBufferPool(ObjectSubclass<imp::TestBufferPool>) @extends BufferPool, crate::Object;
    }

    impl Default for TestBufferPool {
        fn default() -> Self {
            glib::Object::new()
        }
    }

    #[test]
    fn test_pool_options() {
        crate::init().unwrap();
        let pool = TestBufferPool::default();
        assert_eq!(pool.options(), vec!["TEST_OPTION"]);
    }

    #[test]
    fn test_pool_acquire() {
        crate::init().unwrap();
        let pool = TestBufferPool::default();
        let mut config = pool.config();
        config.set_params(None, 1024, 1, 1);
        pool.set_config(config).expect("failed to set pool config");
        pool.set_active(true).expect("failed to activate pool");
        let buffer = pool
            .acquire_buffer(None)
            .expect("failed to acquire buffer from pool");
        assert_eq!(buffer.size(), 2048);
    }

    #[test]
    fn test_pool_free_on_finalize() {
        crate::init().unwrap();
        let pool = TestBufferPool::default();
        let mut config = pool.config();
        config.set_params(None, 1024, 1, 1);
        pool.set_config(config).expect("failed to set pool config");
        pool.set_active(true).expect("failed to activate pool");
        let mut buffer = pool
            .acquire_buffer(None)
            .expect("failed to acquire buffer from pool");
        let finalized = Arc::new(AtomicBool::new(false));
        unsafe {
            ffi::gst_mini_object_weak_ref(
                buffer.make_mut().upcast_mut().as_mut_ptr(),
                Some(buffer_finalized),
                Arc::into_raw(finalized.clone()) as *mut _,
            )
        };
        // return the buffer to the pool
        std::mem::drop(buffer);
        // drop should finalize the buffer pool which frees all allocated buffers
        std::mem::drop(pool);
        assert!(finalized.load(Ordering::SeqCst));
    }

    #[test]
    fn test_pool_free_on_deactivate() {
        crate::init().unwrap();
        let pool = TestBufferPool::default();
        let mut config = pool.config();
        config.set_params(None, 1024, 1, 1);
        pool.set_config(config).expect("failed to set pool config");
        pool.set_active(true).expect("failed to activate pool");
        let mut buffer = pool
            .acquire_buffer(None)
            .expect("failed to acquire buffer from pool");
        let finalized = Arc::new(AtomicBool::new(false));
        unsafe {
            ffi::gst_mini_object_weak_ref(
                buffer.make_mut().upcast_mut().as_mut_ptr(),
                Some(buffer_finalized),
                Arc::into_raw(finalized.clone()) as *mut _,
            )
        };
        // return the buffer to the pool
        std::mem::drop(buffer);
        // de-activating a poll should free all buffers
        pool.set_active(false).expect("failed to de-activate pool");
        assert!(finalized.load(Ordering::SeqCst));
    }

    unsafe extern "C" fn buffer_finalized(
        data: *mut libc::c_void,
        _mini_object: *mut ffi::GstMiniObject,
    ) {
        let finalized = Arc::from_raw(data as *const AtomicBool);
        finalized.store(true, Ordering::SeqCst);
    }
}