Skip to main content

gstreamer/subclass/
allocator.rs

1// Take a look at the license at the top of the repository in the LICENSE file.
2
3use std::ptr;
4
5use glib::{prelude::*, subclass::prelude::*, translate::*};
6
7use super::prelude::*;
8use crate::{AllocationParams, Allocator, ffi};
9
10pub unsafe trait AllocatorImpl:
11    GstObjectImpl + ObjectSubclass<Type: IsA<Allocator>>
12{
13    /// Use `allocator` to allocate a new memory block with memory that is at least
14    /// `size` big.
15    ///
16    /// The optional `params` can specify the prefix and padding for the memory. If
17    /// [`None`] is passed, no flags, no extra prefix/padding and a default alignment is
18    /// used.
19    ///
20    /// The prefix/padding will be filled with 0 if flags contains
21    /// [`MemoryFlags::ZERO_PREFIXED`][crate::MemoryFlags::ZERO_PREFIXED] and [`MemoryFlags::ZERO_PADDED`][crate::MemoryFlags::ZERO_PADDED] respectively.
22    ///
23    /// When `allocator` is [`None`], the default allocator will be used.
24    ///
25    /// The alignment in `params` is given as a bitmask so that `align` + 1 equals
26    /// the amount of bytes to align to. For example, to align to 8 bytes,
27    /// use an alignment of 7.
28    /// ## `size`
29    /// size of the visible memory area
30    /// ## `params`
31    /// optional parameters
32    ///
33    /// # Returns
34    ///
35    /// a new [`Memory`][crate::Memory].
36    unsafe fn alloc(&self, size: usize, params: &AllocationParams) -> *mut ffi::GstMemory {
37        unsafe { self.parent_alloc(size, params) }
38    }
39
40    unsafe fn free(&self, memory: *mut ffi::GstMemory) {
41        unsafe { self.parent_free(memory) }
42    }
43}
44
45pub trait AllocatorImplExt: AllocatorImpl {
46    unsafe fn parent_alloc(&self, size: usize, params: &AllocationParams) -> *mut ffi::GstMemory {
47        unsafe {
48            let data = Self::type_data();
49            let parent_class = data.as_ref().parent_class() as *mut ffi::GstAllocatorClass;
50
51            if let Some(f) = (*parent_class).alloc {
52                f(
53                    self.obj().unsafe_cast_ref::<Allocator>().to_glib_none().0,
54                    size,
55                    mut_override(params.to_glib_none().0),
56                )
57            } else {
58                ptr::null_mut()
59            }
60        }
61    }
62
63    unsafe fn parent_free(&self, memory: *mut ffi::GstMemory) {
64        unsafe {
65            let data = Self::type_data();
66            let parent_class = data.as_ref().parent_class() as *mut ffi::GstAllocatorClass;
67
68            if let Some(f) = (*parent_class).free {
69                f(
70                    self.obj().unsafe_cast_ref::<Allocator>().to_glib_none().0,
71                    memory,
72                )
73            }
74        }
75    }
76}
77
78impl<T: AllocatorImpl> AllocatorImplExt for T {}
79
80unsafe impl<T: AllocatorImpl> IsSubclassable<T> for Allocator {
81    fn class_init(klass: &mut glib::Class<Self>) {
82        Self::parent_class_init::<T>(klass);
83        let klass = klass.as_mut();
84        klass.alloc = Some(alloc::<T>);
85        klass.free = Some(free::<T>);
86    }
87}
88
89unsafe extern "C" fn alloc<T: AllocatorImpl>(
90    ptr: *mut ffi::GstAllocator,
91    size: usize,
92    params: *mut ffi::GstAllocationParams,
93) -> *mut ffi::GstMemory {
94    unsafe {
95        let instance = &*(ptr as *mut T::Instance);
96        let imp = instance.imp();
97
98        let params = &*(params as *mut AllocationParams);
99
100        imp.alloc(size, params)
101    }
102}
103
104unsafe extern "C" fn free<T: AllocatorImpl>(
105    ptr: *mut ffi::GstAllocator,
106    memory: *mut ffi::GstMemory,
107) {
108    unsafe {
109        debug_assert_eq!((*memory).mini_object.refcount, 0);
110
111        let instance = &*(ptr as *mut T::Instance);
112        let imp = instance.imp();
113
114        imp.free(memory);
115    }
116}
117
118#[cfg(test)]
119mod tests {
120    use super::*;
121    use crate::prelude::*;
122
123    // The test allocator below is basically replicating GStreamer's default
124    // sysmem allocator except that the memory allocation is separate from the
125    // memory struct for clarity.
126
127    pub mod imp {
128        use std::alloc;
129
130        use super::*;
131
132        #[repr(C)]
133        struct Memory {
134            mem: ffi::GstMemory,
135            layout: alloc::Layout,
136            data: *mut u8,
137        }
138
139        const LAYOUT: alloc::Layout = alloc::Layout::new::<Memory>();
140
141        #[derive(Default)]
142        pub struct TestAllocator;
143
144        impl ObjectImpl for TestAllocator {}
145        impl GstObjectImpl for TestAllocator {}
146        unsafe impl AllocatorImpl for TestAllocator {
147            unsafe fn alloc(&self, size: usize, params: &AllocationParams) -> *mut ffi::GstMemory {
148                unsafe {
149                    let Some(maxsize) = size
150                        .checked_add(params.prefix())
151                        .and_then(|s| s.checked_add(params.padding()))
152                    else {
153                        return ptr::null_mut();
154                    };
155
156                    let align = params.align() | crate::Memory::default_alignment();
157                    let Ok(layout) = alloc::Layout::from_size_align(maxsize, align + 1) else {
158                        return ptr::null_mut();
159                    };
160
161                    let mem = alloc::alloc(LAYOUT) as *mut Memory;
162
163                    let data = alloc::alloc(layout);
164
165                    if params.prefix() > 0
166                        && params.flags().contains(crate::MemoryFlags::ZERO_PREFIXED)
167                    {
168                        ptr::write_bytes(data, 0, params.prefix());
169                    }
170
171                    if params.flags().contains(crate::MemoryFlags::ZERO_PADDED) {
172                        ptr::write_bytes(data.add(params.prefix()).add(size), 0, params.padding());
173                    }
174
175                    ffi::gst_memory_init(
176                        ptr::addr_of_mut!((*mem).mem),
177                        params.flags().into_glib(),
178                        self.obj().as_ptr() as *mut ffi::GstAllocator,
179                        ptr::null_mut(),
180                        maxsize,
181                        params.align(),
182                        params.prefix(),
183                        size,
184                    );
185                    ptr::write(ptr::addr_of_mut!((*mem).layout), layout);
186                    ptr::write(ptr::addr_of_mut!((*mem).data), data);
187
188                    mem as *mut ffi::GstMemory
189                }
190            }
191
192            unsafe fn free(&self, mem: *mut ffi::GstMemory) {
193                unsafe {
194                    let mem = mem as *mut Memory;
195
196                    if (*mem).mem.parent.is_null() {
197                        alloc::dealloc((*mem).data, (*mem).layout);
198                    }
199                    alloc::dealloc(mem as *mut u8, LAYOUT);
200                }
201            }
202        }
203
204        #[glib::object_subclass]
205        impl ObjectSubclass for TestAllocator {
206            const NAME: &'static str = "TestAllocator";
207            type Type = super::TestAllocator;
208            type ParentType = Allocator;
209
210            fn instance_init(obj: &glib::subclass::InitializingObject<Self>) {
211                static ALLOCATOR_TYPE: &[u8] = b"TestAllocatorMemory\0";
212
213                unsafe {
214                    let allocator = obj.as_ptr() as *mut ffi::GstAllocator;
215
216                    // TODO: This should all be in some kind of trait ideally
217                    (*allocator).mem_type = ALLOCATOR_TYPE.as_ptr() as *const _;
218                    (*allocator).mem_map = Some(TestAllocator::mem_map);
219                    (*allocator).mem_unmap = Some(TestAllocator::mem_unmap);
220                    // mem_copy not set because the fallback already does the right thing
221                    (*allocator).mem_share = Some(TestAllocator::mem_share);
222                    (*allocator).mem_is_span = Some(TestAllocator::mem_is_span);
223                }
224            }
225        }
226
227        impl TestAllocator {
228            unsafe extern "C" fn mem_map(
229                mem: *mut ffi::GstMemory,
230                _maxsize: usize,
231                _flags: ffi::GstMapFlags,
232            ) -> glib::ffi::gpointer {
233                unsafe {
234                    let mem = mem as *mut Memory;
235
236                    let parent = if (*mem).mem.parent.is_null() {
237                        mem
238                    } else {
239                        (*mem).mem.parent as *mut Memory
240                    };
241
242                    // `(*mem).offset` is added to the pointer by `gst_memory_map()`
243                    (*parent).data as *mut _
244                }
245            }
246
247            unsafe extern "C" fn mem_unmap(_mem: *mut ffi::GstMemory) {}
248
249            unsafe extern "C" fn mem_share(
250                mem: *mut ffi::GstMemory,
251                offset: isize,
252                size: isize,
253            ) -> *mut ffi::GstMemory {
254                unsafe {
255                    let mem = mem as *mut Memory;
256
257                    // Basically a re-implementation of _sysmem_share()
258
259                    let parent = if (*mem).mem.parent.is_null() {
260                        mem
261                    } else {
262                        (*mem).mem.parent as *mut Memory
263                    };
264
265                    // Offset and size are actually usizes and the API assumes that negative values simply wrap
266                    // around, so let's cast to usizes here and do wrapping arithmetic.
267                    let offset = offset as usize;
268                    let mut size = size as usize;
269
270                    let new_offset = (*mem).mem.offset.wrapping_add(offset);
271                    debug_assert!(new_offset < (*mem).mem.maxsize);
272
273                    if size == usize::MAX {
274                        size = (*mem).mem.size.wrapping_sub(offset);
275                    }
276                    debug_assert!(new_offset <= usize::MAX - size);
277                    debug_assert!(new_offset + size <= (*mem).mem.maxsize);
278
279                    let sub = alloc::alloc(LAYOUT) as *mut Memory;
280
281                    ffi::gst_memory_init(
282                        sub as *mut ffi::GstMemory,
283                        (*mem).mem.mini_object.flags | ffi::GST_MINI_OBJECT_FLAG_LOCK_READONLY,
284                        (*mem).mem.allocator,
285                        parent as *mut ffi::GstMemory,
286                        (*mem).mem.maxsize,
287                        (*mem).mem.align,
288                        new_offset,
289                        size,
290                    );
291                    // This is never actually accessed
292                    ptr::write(ptr::addr_of_mut!((*sub).data), ptr::null_mut());
293
294                    sub as *mut ffi::GstMemory
295                }
296            }
297
298            unsafe extern "C" fn mem_is_span(
299                mem1: *mut ffi::GstMemory,
300                mem2: *mut ffi::GstMemory,
301                offset: *mut usize,
302            ) -> glib::ffi::gboolean {
303                unsafe {
304                    let mem1 = mem1 as *mut Memory;
305                    let mem2 = mem2 as *mut Memory;
306
307                    // Same parent is checked by `gst_memory_is_span()` already
308                    let parent1 = (*mem1).mem.parent as *mut Memory;
309                    let parent2 = (*mem2).mem.parent as *mut Memory;
310                    debug_assert_eq!(parent1, parent2);
311
312                    if !offset.is_null() {
313                        // Offset that can be used on the parent memory to create a
314                        // shared memory that starts with `mem1`.
315                        //
316                        // This needs to use wrapping arithmetic too as in `mem_share()`.
317                        *offset = (*mem1).mem.offset.wrapping_sub((*parent1).mem.offset);
318                    }
319
320                    // Check if both memories are contiguous.
321                    let is_span = ((*mem1).mem.offset + ((*mem1).mem.size)) == (*mem2).mem.offset;
322
323                    is_span.into_glib()
324                }
325            }
326        }
327    }
328
329    glib::wrapper! {
330        pub struct TestAllocator(ObjectSubclass<imp::TestAllocator>) @extends Allocator, crate::Object;
331    }
332
333    impl Default for TestAllocator {
334        fn default() -> Self {
335            glib::Object::new()
336        }
337    }
338
339    #[test]
340    fn test_allocator_registration() {
341        crate::init().unwrap();
342
343        const TEST_ALLOCATOR_NAME: &str = "TestAllocator";
344
345        let allocator = TestAllocator::default();
346        Allocator::register(TEST_ALLOCATOR_NAME, allocator);
347
348        let allocator = Allocator::find(Some(TEST_ALLOCATOR_NAME));
349
350        assert!(allocator.is_some());
351    }
352
353    #[test]
354    fn test_allocator_alloc() {
355        crate::init().unwrap();
356
357        const SIZE: usize = 1024;
358
359        let allocator = TestAllocator::default();
360
361        let memory = allocator.alloc(SIZE, None).unwrap();
362
363        assert_eq!(memory.size(), SIZE);
364    }
365
366    #[test]
367    fn test_allocator_mem_ops() {
368        crate::init().unwrap();
369
370        let data = [0, 1, 2, 3, 4, 5, 6, 7];
371
372        let allocator = TestAllocator::default();
373
374        let mut memory = allocator.alloc(data.len(), None).unwrap();
375        assert_eq!(memory.size(), data.len());
376
377        {
378            let memory = memory.get_mut().unwrap();
379            let mut map = memory.map_writable().unwrap();
380            map.copy_from_slice(&data);
381        }
382
383        let copy = memory.copy();
384        assert!(copy.parent().is_none());
385
386        {
387            let map1 = memory.map_readable().unwrap();
388            let map2 = copy.map_readable().unwrap();
389            assert_eq!(map1.as_slice(), map2.as_slice());
390        }
391
392        let share = memory.share(..);
393        assert_eq!(share.parent().unwrap().as_ptr(), memory.as_ptr());
394
395        {
396            let map1 = memory.map_readable().unwrap();
397            let map2 = share.map_readable().unwrap();
398            assert_eq!(map1.as_slice(), map2.as_slice());
399        }
400
401        let sub1 = memory.share(..2);
402        assert_eq!(sub1.size(), 2);
403        assert_eq!(sub1.parent().unwrap().as_ptr(), memory.as_ptr());
404
405        {
406            let map = sub1.map_readable().unwrap();
407            assert_eq!(map.as_slice(), &data[..2]);
408        }
409
410        let sub2 = memory.share(2..);
411        assert_eq!(sub2.size(), 6);
412        assert_eq!(sub2.parent().unwrap().as_ptr(), memory.as_ptr());
413
414        {
415            let map = sub2.map_readable().unwrap();
416            assert_eq!(map.as_slice(), &data[2..]);
417        }
418
419        let offset = sub1.is_span(&sub2).unwrap();
420        assert_eq!(offset, 0);
421
422        let sub3 = sub2.share(2..);
423        assert_eq!(sub3.size(), 4);
424        assert_eq!(sub3.parent().unwrap().as_ptr(), memory.as_ptr());
425
426        {
427            let map = sub3.map_readable().unwrap();
428            assert_eq!(map.as_slice(), &data[4..]);
429        }
430    }
431}