gstreamer 0.25.1

Rust bindings for GStreamer
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
// Take a look at the license at the top of the repository in the LICENSE file.

use std::ptr;

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

use super::prelude::*;
use crate::{AllocationParams, Allocator, ffi};

pub unsafe trait AllocatorImpl:
    GstObjectImpl + ObjectSubclass<Type: IsA<Allocator>>
{
    unsafe fn alloc(&self, size: usize, params: &AllocationParams) -> *mut ffi::GstMemory {
        unsafe { self.parent_alloc(size, params) }
    }

    unsafe fn free(&self, memory: *mut ffi::GstMemory) {
        unsafe { self.parent_free(memory) }
    }
}

pub trait AllocatorImplExt: AllocatorImpl {
    unsafe fn parent_alloc(&self, size: usize, params: &AllocationParams) -> *mut ffi::GstMemory {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GstAllocatorClass;

            if let Some(f) = (*parent_class).alloc {
                f(
                    self.obj().unsafe_cast_ref::<Allocator>().to_glib_none().0,
                    size,
                    mut_override(params.to_glib_none().0),
                )
            } else {
                ptr::null_mut()
            }
        }
    }

    unsafe fn parent_free(&self, memory: *mut ffi::GstMemory) {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GstAllocatorClass;

            if let Some(f) = (*parent_class).free {
                f(
                    self.obj().unsafe_cast_ref::<Allocator>().to_glib_none().0,
                    memory,
                )
            }
        }
    }
}

impl<T: AllocatorImpl> AllocatorImplExt for T {}

unsafe impl<T: AllocatorImpl> IsSubclassable<T> for Allocator {
    fn class_init(klass: &mut glib::Class<Self>) {
        Self::parent_class_init::<T>(klass);
        let klass = klass.as_mut();
        klass.alloc = Some(alloc::<T>);
        klass.free = Some(free::<T>);
    }
}

unsafe extern "C" fn alloc<T: AllocatorImpl>(
    ptr: *mut ffi::GstAllocator,
    size: usize,
    params: *mut ffi::GstAllocationParams,
) -> *mut ffi::GstMemory {
    unsafe {
        let instance = &*(ptr as *mut T::Instance);
        let imp = instance.imp();

        let params = &*(params as *mut AllocationParams);

        imp.alloc(size, params)
    }
}

unsafe extern "C" fn free<T: AllocatorImpl>(
    ptr: *mut ffi::GstAllocator,
    memory: *mut ffi::GstMemory,
) {
    unsafe {
        debug_assert_eq!((*memory).mini_object.refcount, 0);

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

        imp.free(memory);
    }
}

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

    // The test allocator below is basically replicating GStreamer's default
    // sysmem allocator except that the memory allocation is separate from the
    // memory struct for clarity.

    pub mod imp {
        use glib::translate::*;
        use std::alloc;

        use super::*;

        #[repr(C)]
        struct Memory {
            mem: ffi::GstMemory,
            layout: alloc::Layout,
            data: *mut u8,
        }

        const LAYOUT: alloc::Layout = alloc::Layout::new::<Memory>();

        #[derive(Default)]
        pub struct TestAllocator;

        impl ObjectImpl for TestAllocator {}
        impl GstObjectImpl for TestAllocator {}
        unsafe impl AllocatorImpl for TestAllocator {
            unsafe fn alloc(&self, size: usize, params: &AllocationParams) -> *mut ffi::GstMemory {
                unsafe {
                    let Some(maxsize) = size
                        .checked_add(params.prefix())
                        .and_then(|s| s.checked_add(params.padding()))
                    else {
                        return ptr::null_mut();
                    };

                    let align = params.align() | crate::Memory::default_alignment();
                    let Ok(layout) = alloc::Layout::from_size_align(maxsize, align + 1) else {
                        return ptr::null_mut();
                    };

                    let mem = alloc::alloc(LAYOUT) as *mut Memory;

                    let data = alloc::alloc(layout);

                    if params.prefix() > 0
                        && params.flags().contains(crate::MemoryFlags::ZERO_PREFIXED)
                    {
                        ptr::write_bytes(data, 0, params.prefix());
                    }

                    if params.flags().contains(crate::MemoryFlags::ZERO_PADDED) {
                        ptr::write_bytes(data.add(params.prefix()).add(size), 0, params.padding());
                    }

                    ffi::gst_memory_init(
                        ptr::addr_of_mut!((*mem).mem),
                        params.flags().into_glib(),
                        self.obj().as_ptr() as *mut ffi::GstAllocator,
                        ptr::null_mut(),
                        maxsize,
                        params.align(),
                        params.prefix(),
                        size,
                    );
                    ptr::write(ptr::addr_of_mut!((*mem).layout), layout);
                    ptr::write(ptr::addr_of_mut!((*mem).data), data);

                    mem as *mut ffi::GstMemory
                }
            }

            unsafe fn free(&self, mem: *mut ffi::GstMemory) {
                unsafe {
                    let mem = mem as *mut Memory;

                    if (*mem).mem.parent.is_null() {
                        alloc::dealloc((*mem).data, (*mem).layout);
                        ptr::drop_in_place(ptr::addr_of_mut!((*mem).layout));
                    }
                    alloc::dealloc(mem as *mut u8, LAYOUT);
                }
            }
        }

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

            fn instance_init(obj: &glib::subclass::InitializingObject<Self>) {
                static ALLOCATOR_TYPE: &[u8] = b"TestAllocatorMemory\0";

                unsafe {
                    let allocator = obj.as_ptr() as *mut ffi::GstAllocator;

                    // TODO: This should all be in some kind of trait ideally
                    (*allocator).mem_type = ALLOCATOR_TYPE.as_ptr() as *const _;
                    (*allocator).mem_map = Some(TestAllocator::mem_map);
                    (*allocator).mem_unmap = Some(TestAllocator::mem_unmap);
                    // mem_copy not set because the fallback already does the right thing
                    (*allocator).mem_share = Some(TestAllocator::mem_share);
                    (*allocator).mem_is_span = Some(TestAllocator::mem_is_span);
                }
            }
        }

        impl TestAllocator {
            unsafe extern "C" fn mem_map(
                mem: *mut ffi::GstMemory,
                _maxsize: usize,
                _flags: ffi::GstMapFlags,
            ) -> glib::ffi::gpointer {
                unsafe {
                    let mem = mem as *mut Memory;

                    let parent = if (*mem).mem.parent.is_null() {
                        mem
                    } else {
                        (*mem).mem.parent as *mut Memory
                    };

                    // `(*mem).offset` is added to the pointer by `gst_memory_map()`
                    (*parent).data as *mut _
                }
            }

            unsafe extern "C" fn mem_unmap(_mem: *mut ffi::GstMemory) {}

            unsafe extern "C" fn mem_share(
                mem: *mut ffi::GstMemory,
                offset: isize,
                size: isize,
            ) -> *mut ffi::GstMemory {
                unsafe {
                    let mem = mem as *mut Memory;

                    // Basically a re-implementation of _sysmem_share()

                    let parent = if (*mem).mem.parent.is_null() {
                        mem
                    } else {
                        (*mem).mem.parent as *mut Memory
                    };

                    // Offset and size are actually usizes and the API assumes that negative values simply wrap
                    // around, so let's cast to usizes here and do wrapping arithmetic.
                    let offset = offset as usize;
                    let mut size = size as usize;

                    let new_offset = (*mem).mem.offset.wrapping_add(offset);
                    debug_assert!(new_offset < (*mem).mem.maxsize);

                    if size == usize::MAX {
                        size = (*mem).mem.size.wrapping_sub(offset);
                    }
                    debug_assert!(new_offset <= usize::MAX - size);
                    debug_assert!(new_offset + size <= (*mem).mem.maxsize);

                    let sub = alloc::alloc(LAYOUT) as *mut Memory;

                    ffi::gst_memory_init(
                        sub as *mut ffi::GstMemory,
                        (*mem).mem.mini_object.flags | ffi::GST_MINI_OBJECT_FLAG_LOCK_READONLY,
                        (*mem).mem.allocator,
                        parent as *mut ffi::GstMemory,
                        (*mem).mem.maxsize,
                        (*mem).mem.align,
                        new_offset,
                        size,
                    );
                    // This is never actually accessed
                    ptr::write(ptr::addr_of_mut!((*sub).data), ptr::null_mut());

                    sub as *mut ffi::GstMemory
                }
            }

            unsafe extern "C" fn mem_is_span(
                mem1: *mut ffi::GstMemory,
                mem2: *mut ffi::GstMemory,
                offset: *mut usize,
            ) -> glib::ffi::gboolean {
                unsafe {
                    let mem1 = mem1 as *mut Memory;
                    let mem2 = mem2 as *mut Memory;

                    // Same parent is checked by `gst_memory_is_span()` already
                    let parent1 = (*mem1).mem.parent as *mut Memory;
                    let parent2 = (*mem2).mem.parent as *mut Memory;
                    debug_assert_eq!(parent1, parent2);

                    if !offset.is_null() {
                        // Offset that can be used on the parent memory to create a
                        // shared memory that starts with `mem1`.
                        //
                        // This needs to use wrapping arithmetic too as in `mem_share()`.
                        *offset = (*mem1).mem.offset.wrapping_sub((*parent1).mem.offset);
                    }

                    // Check if both memories are contiguous.
                    let is_span = ((*mem1).mem.offset + ((*mem1).mem.size)) == (*mem2).mem.offset;

                    is_span.into_glib()
                }
            }
        }
    }

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

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

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

        const TEST_ALLOCATOR_NAME: &str = "TestAllocator";

        let allocator = TestAllocator::default();
        Allocator::register(TEST_ALLOCATOR_NAME, allocator);

        let allocator = Allocator::find(Some(TEST_ALLOCATOR_NAME));

        assert!(allocator.is_some());
    }

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

        const SIZE: usize = 1024;

        let allocator = TestAllocator::default();

        let memory = allocator.alloc(SIZE, None).unwrap();

        assert_eq!(memory.size(), SIZE);
    }

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

        let data = [0, 1, 2, 3, 4, 5, 6, 7];

        let allocator = TestAllocator::default();

        let mut memory = allocator.alloc(data.len(), None).unwrap();
        assert_eq!(memory.size(), data.len());

        {
            let memory = memory.get_mut().unwrap();
            let mut map = memory.map_writable().unwrap();
            map.copy_from_slice(&data);
        }

        let copy = memory.copy();
        assert!(copy.parent().is_none());

        {
            let map1 = memory.map_readable().unwrap();
            let map2 = copy.map_readable().unwrap();
            assert_eq!(map1.as_slice(), map2.as_slice());
        }

        let share = memory.share(..);
        assert_eq!(share.parent().unwrap().as_ptr(), memory.as_ptr());

        {
            let map1 = memory.map_readable().unwrap();
            let map2 = share.map_readable().unwrap();
            assert_eq!(map1.as_slice(), map2.as_slice());
        }

        let sub1 = memory.share(..2);
        assert_eq!(sub1.size(), 2);
        assert_eq!(sub1.parent().unwrap().as_ptr(), memory.as_ptr());

        {
            let map = sub1.map_readable().unwrap();
            assert_eq!(map.as_slice(), &data[..2]);
        }

        let sub2 = memory.share(2..);
        assert_eq!(sub2.size(), 6);
        assert_eq!(sub2.parent().unwrap().as_ptr(), memory.as_ptr());

        {
            let map = sub2.map_readable().unwrap();
            assert_eq!(map.as_slice(), &data[2..]);
        }

        let offset = sub1.is_span(&sub2).unwrap();
        assert_eq!(offset, 0);

        let sub3 = sub2.share(2..);
        assert_eq!(sub3.size(), 4);
        assert_eq!(sub3.parent().unwrap().as_ptr(), memory.as_ptr());

        {
            let map = sub3.map_readable().unwrap();
            assert_eq!(map.as_slice(), &data[4..]);
        }
    }
}