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

use std::{fmt, ops::ControlFlow, ptr};

use glib::translate::*;

use crate::{Buffer, BufferRef};

mini_object_wrapper!(BufferList, BufferListRef, ffi::GstBufferList, || {
    ffi::gst_buffer_list_get_type()
});

impl BufferList {
    #[doc(alias = "gst_buffer_list_new")]
    pub fn new() -> Self {
        assert_initialized_main_thread!();
        unsafe { from_glib_full(ffi::gst_buffer_list_new()) }
    }

    #[doc(alias = "gst_buffer_list_new_sized")]
    pub fn new_sized(size: usize) -> Self {
        assert_initialized_main_thread!();
        unsafe { from_glib_full(ffi::gst_buffer_list_new_sized(size as u32)) }
    }
}

impl BufferListRef {
    #[doc(alias = "gst_buffer_list_insert")]
    pub fn insert(&mut self, idx: i32, buffer: Buffer) {
        unsafe {
            ffi::gst_buffer_list_insert(self.as_mut_ptr(), idx, buffer.into_glib_ptr());
        }
    }

    #[doc(alias = "gst_buffer_list_add")]
    pub fn add(&mut self, buffer: Buffer) {
        self.insert(-1, buffer);
    }

    #[doc(alias = "gst_buffer_list_copy_deep")]
    pub fn copy_deep(&self) -> BufferList {
        unsafe { from_glib_full(ffi::gst_buffer_list_copy_deep(self.as_ptr())) }
    }

    #[doc(alias = "gst_buffer_list_remove")]
    pub fn remove(&mut self, idx: u32, len: u32) {
        let n = self.len() as u32;
        assert!(idx < n);
        assert!(idx.checked_add(len).unwrap() <= n);

        unsafe { ffi::gst_buffer_list_remove(self.as_mut_ptr(), idx, len) }
    }

    #[doc(alias = "gst_buffer_list_get")]
    pub fn get(&self, idx: u32) -> Option<&BufferRef> {
        unsafe {
            if idx as usize >= self.len() {
                return None;
            }
            let ptr = ffi::gst_buffer_list_get(self.as_mut_ptr(), idx);
            Some(BufferRef::from_ptr(ptr))
        }
    }

    #[doc(alias = "gst_buffer_list_get")]
    pub fn get_owned(&self, idx: u32) -> Option<Buffer> {
        unsafe {
            if idx as usize >= self.len() {
                return None;
            }
            let ptr = ffi::gst_buffer_list_get(self.as_mut_ptr(), idx);
            Some(from_glib_none(ptr))
        }
    }

    #[doc(alias = "gst_buffer_list_get_writable")]
    #[doc(alias = "get_writable")]
    pub fn get_mut(&mut self, idx: u32) -> Option<&mut BufferRef> {
        unsafe {
            if idx as usize >= self.len() {
                return None;
            }
            let ptr = ffi::gst_buffer_list_get_writable(self.as_mut_ptr(), idx);
            Some(BufferRef::from_mut_ptr(ptr))
        }
    }

    #[doc(alias = "gst_buffer_list_length")]
    pub fn len(&self) -> usize {
        unsafe { ffi::gst_buffer_list_length(self.as_mut_ptr()) as usize }
    }

    #[doc(alias = "gst_buffer_list_calculate_size")]
    pub fn calculate_size(&self) -> usize {
        unsafe { ffi::gst_buffer_list_calculate_size(self.as_mut_ptr()) }
    }

    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    pub fn iter(&self) -> Iter {
        Iter::new(self)
    }

    pub fn iter_owned(&self) -> IterOwned {
        IterOwned::new(self)
    }

    #[doc(alias = "gst_buffer_list_foreach")]
    pub fn foreach<F: FnMut(&Buffer, u32) -> ControlFlow<(), ()>>(&self, func: F) -> bool {
        unsafe extern "C" fn trampoline<F: FnMut(&Buffer, u32) -> ControlFlow<(), ()>>(
            buffer: *mut *mut ffi::GstBuffer,
            idx: u32,
            user_data: glib::ffi::gpointer,
        ) -> glib::ffi::gboolean {
            let func = user_data as *mut F;
            let res = (*func)(&Buffer::from_glib_borrow(*buffer), idx);

            matches!(res, ControlFlow::Continue(_)).into_glib()
        }

        unsafe {
            let func_ptr: &F = &func;

            from_glib(ffi::gst_buffer_list_foreach(
                self.as_ptr() as *mut _,
                Some(trampoline::<F>),
                func_ptr as *const _ as *mut _,
            ))
        }
    }

    #[doc(alias = "gst_buffer_list_foreach")]
    pub fn foreach_mut<F: FnMut(Buffer, u32) -> ControlFlow<Option<Buffer>, Option<Buffer>>>(
        &mut self,
        func: F,
    ) -> bool {
        unsafe extern "C" fn trampoline<
            F: FnMut(Buffer, u32) -> ControlFlow<Option<Buffer>, Option<Buffer>>,
        >(
            buffer: *mut *mut ffi::GstBuffer,
            idx: u32,
            user_data: glib::ffi::gpointer,
        ) -> glib::ffi::gboolean {
            let func = user_data as *mut F;
            let res = (*func)(
                Buffer::from_glib_full(ptr::replace(
                    buffer as *mut *const ffi::GstBuffer,
                    ptr::null_mut::<ffi::GstBuffer>(),
                )),
                idx,
            );

            let (cont, res_buffer) = match res {
                ControlFlow::Continue(res_buffer) => (true, res_buffer),
                ControlFlow::Break(res_buffer) => (false, res_buffer),
            };

            match res_buffer {
                None => {
                    *buffer = ptr::null_mut();
                }
                Some(new_buffer) => {
                    *buffer = new_buffer.into_glib_ptr();
                }
            }

            cont.into_glib()
        }

        unsafe {
            let func_ptr: &F = &func;

            from_glib(ffi::gst_buffer_list_foreach(
                self.as_ptr() as *mut _,
                Some(trampoline::<F>),
                func_ptr as *const _ as *mut _,
            ))
        }
    }
}

impl Default for BufferList {
    fn default() -> Self {
        Self::new()
    }
}

impl fmt::Debug for BufferList {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        BufferListRef::fmt(self, f)
    }
}

impl fmt::Debug for BufferListRef {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use crate::{utils::Displayable, ClockTime};

        let size = self.iter().map(|b| b.size()).sum::<usize>();
        let (pts, dts) = self
            .get(0)
            .map(|b| (b.pts(), b.dts()))
            .unwrap_or((ClockTime::NONE, ClockTime::NONE));

        f.debug_struct("BufferList")
            .field("ptr", &self.as_ptr())
            .field("buffers", &self.len())
            .field("pts", &pts.display())
            .field("dts", &dts.display())
            .field("size", &size)
            .finish()
    }
}

macro_rules! define_iter(
    ($name:ident, $styp:ty, $get_item:expr) => {
    #[derive(Debug)]
    pub struct $name<'a> {
        list: &'a BufferListRef,
        idx: usize,
        size: usize,
    }

    impl<'a> $name<'a> {
        fn new(list: &'a BufferListRef) -> $name<'a> {
            skip_assert_initialized!();
            $name {
                list,
                idx: 0,
                size: list.len() as usize,
            }
        }
    }

    #[allow(clippy::redundant_closure_call)]
    impl<'a> Iterator for $name<'a> {
        type Item = $styp;

        fn next(&mut self) -> Option<Self::Item> {
            if self.idx >= self.size {
                return None;
            }

            let item = $get_item(self.list, self.idx as u32).unwrap();
            self.idx += 1;

            Some(item)
        }

        fn size_hint(&self) -> (usize, Option<usize>) {
            let remaining = self.size - self.idx;

            (remaining, Some(remaining))
        }

        fn count(self) -> usize {
            self.size - self.idx
        }

        fn nth(&mut self, n: usize) -> Option<Self::Item> {
            let (end, overflow) = self.idx.overflowing_add(n);
            if end >= self.size || overflow {
                self.idx = self.size;
                None
            } else {
                self.idx = end + 1;
                Some($get_item(self.list, end as u32).unwrap())
            }
        }

        fn last(self) -> Option<Self::Item> {
            if self.idx == self.size {
                None
            } else {
                Some($get_item(self.list, self.size as u32 - 1).unwrap())
            }
        }
    }

    #[allow(clippy::redundant_closure_call)]
    impl<'a> DoubleEndedIterator for $name<'a> {
        fn next_back(&mut self) -> Option<Self::Item> {
            if self.idx == self.size {
                return None;
            }

            self.size -= 1;
            Some($get_item(self.list, self.size as u32).unwrap())
        }

        fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
            let (end, overflow) = self.size.overflowing_sub(n);
            if end <= self.idx || overflow {
                self.idx = self.size;
                None
            } else {
                self.size = end - 1;
                Some($get_item(self.list, self.size as u32).unwrap())
            }
        }
    }

    impl<'a> ExactSizeIterator for $name<'a> {}
    impl<'a> std::iter::FusedIterator for $name<'a> {}
    }
);

define_iter!(Iter, &'a BufferRef, |list: &'a BufferListRef, idx| {
    list.get(idx)
});

define_iter!(IterOwned, Buffer, |list: &BufferListRef, idx| {
    list.get_owned(idx)
});

impl<'a> IntoIterator for &'a BufferListRef {
    type IntoIter = Iter<'a>;
    type Item = &'a BufferRef;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl From<Buffer> for BufferList {
    fn from(value: Buffer) -> Self {
        skip_assert_initialized!();

        let mut list = BufferList::new_sized(1);
        {
            let list = list.get_mut().unwrap();
            list.add(value);
        }
        list
    }
}

impl<const N: usize> From<[Buffer; N]> for BufferList {
    fn from(value: [Buffer; N]) -> Self {
        skip_assert_initialized!();

        let mut list = BufferList::new_sized(N);
        {
            let list = list.get_mut().unwrap();
            value.into_iter().for_each(|b| list.add(b));
        }
        list
    }
}

impl std::iter::FromIterator<Buffer> for BufferList {
    fn from_iter<T: IntoIterator<Item = Buffer>>(iter: T) -> Self {
        assert_initialized_main_thread!();

        let iter = iter.into_iter();

        let mut list = BufferList::new_sized(iter.size_hint().0);

        {
            let list = list.get_mut().unwrap();
            iter.for_each(|b| list.add(b));
        }

        list
    }
}

impl std::iter::Extend<Buffer> for BufferListRef {
    fn extend<T: IntoIterator<Item = Buffer>>(&mut self, iter: T) {
        iter.into_iter().for_each(|b| self.add(b));
    }
}

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

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

        let mut buffer_list = BufferList::new();
        {
            let buffer_list = buffer_list.get_mut().unwrap();
            let mut buffer = Buffer::new();
            buffer.get_mut().unwrap().set_pts(ClockTime::ZERO);
            buffer_list.add(buffer);

            let mut buffer = Buffer::new();
            buffer.get_mut().unwrap().set_pts(ClockTime::SECOND);
            buffer_list.add(buffer);
        }

        let mut res = vec![];
        buffer_list.foreach(|buffer, idx| {
            res.push((buffer.pts(), idx));
            ControlFlow::Continue(())
        });

        assert_eq!(
            res,
            &[(Some(ClockTime::ZERO), 0), (Some(ClockTime::SECOND), 1)]
        );
    }

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

        let mut buffer_list = BufferList::new();
        {
            let buffer_list = buffer_list.get_mut().unwrap();
            let mut buffer = Buffer::new();
            buffer.get_mut().unwrap().set_pts(ClockTime::ZERO);
            buffer_list.add(buffer);

            let mut buffer = Buffer::new();
            buffer.get_mut().unwrap().set_pts(ClockTime::SECOND);
            buffer_list.add(buffer);

            let mut buffer = Buffer::new();
            buffer.get_mut().unwrap().set_pts(2 * ClockTime::SECOND);
            buffer_list.add(buffer);
        }

        let mut res = vec![];
        buffer_list.get_mut().unwrap().foreach_mut(|buffer, idx| {
            res.push((buffer.pts(), idx));

            if let Some(ClockTime::ZERO) = buffer.pts() {
                ControlFlow::Continue(Some(buffer))
            } else if let Some(ClockTime::SECOND) = buffer.pts() {
                ControlFlow::Continue(None)
            } else {
                let mut new_buffer = Buffer::new();
                new_buffer.get_mut().unwrap().set_pts(3 * ClockTime::SECOND);
                ControlFlow::Continue(Some(new_buffer))
            }
        });

        assert_eq!(
            res,
            &[
                (Some(ClockTime::ZERO), 0),
                (Some(ClockTime::SECOND), 1),
                (Some(2 * ClockTime::SECOND), 1)
            ]
        );

        let mut res = vec![];
        buffer_list.foreach(|buffer, idx| {
            res.push((buffer.pts(), idx));
            ControlFlow::Continue(())
        });

        assert_eq!(
            res,
            &[(Some(ClockTime::ZERO), 0), (Some(3 * ClockTime::SECOND), 1)]
        );

        // Try removing buffers from inside foreach_mut
        let mut buffer_list = BufferList::new();
        for i in 0..10 {
            let buffer_list = buffer_list.get_mut().unwrap();
            let mut buffer = Buffer::new();
            buffer.get_mut().unwrap().set_pts(i * ClockTime::SECOND);
            buffer_list.add(buffer);
        }

        assert_eq!(buffer_list.len(), 10);

        let buffer_list_ref = buffer_list.make_mut();

        buffer_list_ref.foreach_mut(|buf, _n| {
            let keep_packet = (buf.pts().unwrap() / ClockTime::SECOND) % 3 != 0;
            ControlFlow::Continue(keep_packet.then_some(buf))
        });

        assert_eq!(buffer_list.len(), 6);

        let res = buffer_list
            .iter()
            .map(|buf| buf.pts().unwrap() / ClockTime::SECOND)
            .collect::<Vec<_>>();

        assert_eq!(res, &[1, 2, 4, 5, 7, 8]);
    }
}