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

use serde::de::{Deserialize, Deserializer};
use serde::ser::{Serialize, SerializeStruct, Serializer};

use crate::Buffer;
use crate::BufferList;
use crate::Caps;
use crate::Sample;
use crate::SampleRef;
use crate::Segment;
use crate::Structure;

impl<'a> Serialize for SampleRef {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let mut sample = serializer.serialize_struct("Sample", 5)?;
        sample.serialize_field("buffer", &self.buffer())?;
        sample.serialize_field("buffer_list", &self.buffer_list())?;
        sample.serialize_field("caps", &self.caps())?;
        sample.serialize_field("segment", &self.segment())?;
        sample.serialize_field("info", &self.info())?;
        sample.end()
    }
}

impl<'a> Serialize for Sample {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        self.as_ref().serialize(serializer)
    }
}

#[derive(serde::Deserialize)]
struct SampleDe {
    buffer: Option<Buffer>,
    buffer_list: Option<BufferList>,
    caps: Option<Caps>,
    segment: Option<Segment>,
    info: Option<Structure>,
}

impl From<SampleDe> for Sample {
    fn from(buf_de: SampleDe) -> Self {
        skip_assert_initialized!();
        let mut builder = Sample::builder();

        if let Some(buffer) = buf_de.buffer.as_ref() {
            builder = builder.buffer(buffer);
        }

        if let Some(buffer_list) = buf_de.buffer_list.as_ref() {
            builder = builder.buffer_list(buffer_list);
        }

        if let Some(caps) = buf_de.caps.as_ref() {
            builder = builder.caps(caps);
        }

        if let Some(segment) = buf_de.segment.as_ref() {
            builder = builder.segment(segment);
        }

        if let Some(info) = buf_de.info {
            builder = builder.info(info);
        }

        builder.build()
    }
}

impl<'de> Deserialize<'de> for Sample {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        skip_assert_initialized!();
        SampleDe::deserialize(deserializer).map(|sample_de| sample_de.into())
    }
}

#[cfg(test)]
mod tests {
    use crate::Buffer;
    use crate::Caps;
    use crate::ClockTime;
    use crate::Format;
    use crate::GenericFormattedValue;
    use crate::Sample;
    use crate::Segment;
    use crate::SegmentFlags;
    use crate::Structure;

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

        let pretty_config = ron::ser::PrettyConfig::new().with_new_line("".to_string());

        let sample = {
            let mut buffer = Buffer::from_slice(vec![1, 2, 3, 4]);
            {
                let buffer = buffer.get_mut().unwrap();
                buffer.set_pts(1.into());
                buffer.set_offset(0);
                buffer.set_offset_end(4);
                buffer.set_duration(4.into());
            }

            let caps = Caps::builder("sample/caps")
                .field("int", &12)
                .field("bool", &true)
                .build();

            let mut segment = Segment::new();
            segment.set_flags(SegmentFlags::RESET | SegmentFlags::SEGMENT);
            segment.set_rate(1f64);
            segment.set_applied_rate(0.9f64);
            segment.set_format(Format::Time);
            segment.set_base(GenericFormattedValue::Time(ClockTime::from_nseconds(123)));
            segment.set_offset(GenericFormattedValue::Time(ClockTime::from_nseconds(42)));
            segment.set_start(GenericFormattedValue::Time(ClockTime::from_nseconds(1024)));
            segment.set_stop(GenericFormattedValue::Time(ClockTime::from_nseconds(2048)));
            segment.set_time(GenericFormattedValue::Time(ClockTime::from_nseconds(1042)));
            segment.set_position(GenericFormattedValue::Time(ClockTime::from_nseconds(256)));
            segment.set_duration(GenericFormattedValue::Time(ClockTime::none()));

            let info = Structure::builder("sample.info")
                .field("f3", &123i32)
                .build();

            Sample::builder()
                .buffer(&buffer)
                .caps(&caps)
                .segment(&segment)
                .info(info)
                .build()
        };

        let res = ron::ser::to_string_pretty(&sample, pretty_config.clone());
        assert_eq!(
            Ok(concat!(
                "(",
                "    buffer: Some((",
                "        pts: Some(1),",
                "        dts: None,",
                "        duration: Some(4),",
                "        offset: 0,",
                "        offset_end: 4,",
                "        flags: (",
                "            bits: 0,",
                "        ),",
                "        buffer: \"AQIDBA==\",",
                "    )),",
                "    buffer_list: None,",
                "    caps: Some(Some([",
                "        ((\"sample/caps\", [",
                "            (\"int\", \"i32\", 12),",
                "            (\"bool\", \"bool\", true),",
                "        ]), None),",
                "    ])),",
                "    segment: Some((",
                "        flags: (",
                "            bits: 9,",
                "        ),",
                "        rate: 1,",
                "        applied_rate: 0.9,",
                "        format: Time,",
                "        base: 123,",
                "        offset: 42,",
                "        start: 1024,",
                "        stop: 2048,",
                "        time: 1042,",
                "        position: 256,",
                "        duration: -1,",
                "    )),",
                "    info: Some((\"sample.info\", [",
                "        (\"f3\", \"i32\", 123),",
                "    ])),",
                ")"
            )
            .to_owned()),
            res
        );

        let sample = {
            let mut buffer = Buffer::from_slice(vec![1, 2, 3, 4]);
            {
                let buffer = buffer.get_mut().unwrap();
                buffer.set_pts(1.into());
                buffer.set_offset(0);
                buffer.set_offset_end(4);
                buffer.set_duration(4.into());
            }
            Sample::builder().buffer(&buffer).build()
        };

        // `Sample`'s `Segment` is allocated in GStreamer 1.x, should be fixed in version 2.0

        let res = ron::ser::to_string_pretty(&sample, pretty_config);
        assert_eq!(
            Ok(concat!(
                "(",
                "    buffer: Some((",
                "        pts: Some(1),",
                "        dts: None,",
                "        duration: Some(4),",
                "        offset: 0,",
                "        offset_end: 4,",
                "        flags: (",
                "            bits: 0,",
                "        ),",
                "        buffer: \"AQIDBA==\",",
                "    )),",
                "    buffer_list: None,",
                "    caps: None,",
                "    segment: Some((",
                "        flags: (",
                "            bits: 0,",
                "        ),",
                "        rate: 1,",
                "        applied_rate: 1,",
                "        format: Time,",
                "        base: 0,",
                "        offset: 0,",
                "        start: 0,",
                "        stop: -1,",
                "        time: 0,",
                "        position: 0,",
                "        duration: -1,",
                "    )),",
                "    info: None,",
                ")"
            )
            .to_owned()),
            res
        );
    }

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

        let buffer_ron = r#"
            (
                buffer: Some((
                    pts: Some(1),
                    dts: None,
                    duration: Some(4),
                    offset: 0,
                    offset_end: 4,
                    flags: (
                        bits: 0,
                    ),
                    buffer: "AQIDBA==",
                )),
                buffer_list: None,
                caps: Some(Some([
                    (("sample/caps", [
                        ("int", "i32", 12),
                        ("bool", "bool", true),
                    ]), None),
                ])),
                segment: Some((
                    flags: (
                        bits: 0,
                    ),
                    rate: 1,
                    applied_rate: 0.9,
                    format: Time,
                    base: 123,
                    offset: 42,
                    start: 1024,
                    stop: 2048,
                    time: 1042,
                    position: 256,
                    duration: -1,
                )),
                info: Some(("sample.info", [
                    ("f3", "i32", 123),
                ])),
            )"#;
        let sample: Sample = ron::de::from_str(buffer_ron).unwrap();
        let buffer = sample.buffer().unwrap();
        assert_eq!(buffer.pts(), 1.into());
        assert_eq!(buffer.offset_end(), 4);
        {
            let data = buffer.map_readable().unwrap();
            assert_eq!(data.as_slice(), vec![1, 2, 3, 4].as_slice());
        }
        assert!(sample.buffer_list().is_none());
        assert!(sample.caps().is_some());
        assert!(sample.segment().is_some());
        assert!(sample.info().is_some());

        let buffer_ron = r#"
            (
                buffer: None,
                buffer_list: Some([
                    (
                        pts: Some(1),
                        dts: None,
                        duration: Some(4),
                        offset: 0,
                        offset_end: 4,
                        flags: (
                            bits: 0,
                        ),
                        buffer: "AQIDBA==",
                    ),
                ]),
                caps: None,
                segment: None,
                info: None,
            )"#;
        let sample: Sample = ron::de::from_str(buffer_ron).unwrap();
        assert!(sample.buffer().is_none());
        assert!(sample.buffer_list().is_some());
        assert!(sample.caps().is_none());
        // Not true in GStreamer 1.x, should be fixed in version 2.0
        //assert!(sample.get_segment().is_none());
        assert!(sample.info().is_none());
    }

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

        // Segment present
        let sample = {
            let mut buffer = Buffer::from_slice(vec![1, 2, 3, 4]);
            {
                let buffer = buffer.get_mut().unwrap();
                buffer.set_pts(1.into());
                buffer.set_offset(0);
                buffer.set_offset_end(4);
                buffer.set_duration(4.into());
            }

            let caps = Caps::builder("sample/caps")
                .field("int", &12)
                .field("bool", &true)
                .build();

            let mut segment = Segment::new();
            segment.set_flags(SegmentFlags::RESET | SegmentFlags::SEGMENT);
            segment.set_rate(1f64);
            segment.set_applied_rate(0.9f64);
            segment.set_format(Format::Time);
            segment.set_base(GenericFormattedValue::Time(ClockTime::from_nseconds(123)));
            segment.set_offset(GenericFormattedValue::Time(ClockTime::from_nseconds(42)));
            segment.set_start(GenericFormattedValue::Time(ClockTime::from_nseconds(1024)));
            segment.set_stop(GenericFormattedValue::Time(ClockTime::from_nseconds(2048)));
            segment.set_time(GenericFormattedValue::Time(ClockTime::from_nseconds(1042)));
            segment.set_position(GenericFormattedValue::Time(ClockTime::from_nseconds(256)));
            segment.set_duration(GenericFormattedValue::Time(ClockTime::none()));

            let info = Structure::builder("sample.info")
                .field("f3", &123i32)
                .build();

            Sample::builder()
                .buffer(&buffer)
                .caps(&caps)
                .segment(&segment)
                .info(info)
                .build()
        };
        let sample_ser = ron::ser::to_string(&sample).unwrap();
        let sample_de: Sample = ron::de::from_str(sample_ser.as_str()).unwrap();
        let buffer_de = sample_de.buffer().unwrap();
        assert_eq!(buffer_de.pts(), 1.into());
        assert_eq!(buffer_de.offset_end(), 4);
        {
            let data = buffer_de.map_readable().unwrap();
            assert_eq!(data.as_slice(), vec![1, 2, 3, 4].as_slice());
        }
        assert!(sample_de.buffer_list().is_none());
        assert!(sample_de.caps().is_some());
        assert!(sample_de.segment().is_some());
        assert!(sample_de.info().is_some());
    }
}