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

use std::ffi::CStr;
use std::str;

use glib::translate::{from_glib, IntoGlib};

use once_cell::sync::Lazy;

/// List of all audio formats, for use in template caps strings.
///
/// Formats are sorted by decreasing "quality", using these criteria by priority:
///  - depth
///  - width
///  - Float > Signed > Unsigned
///  - native endianness preferred
#[cfg(feature = "v1_18")]
pub static AUDIO_FORMATS_ALL: Lazy<Box<[crate::AudioFormat]>> = Lazy::new(|| unsafe {
    let mut len: u32 = 0;
    let mut res = Vec::with_capacity(len as usize);
    let formats = ffi::gst_audio_formats_raw(&mut len);
    for i in 0..len {
        let format = formats.offset(i as isize);
        res.push(from_glib(*format));
    }
    res.into_boxed_slice()
});

#[cfg(not(feature = "v1_18"))]
pub static AUDIO_FORMATS_ALL: Lazy<Box<[crate::AudioFormat]>> = Lazy::new(|| {
    #[cfg(target_endian = "little")]
    {
        Box::new([
            crate::AudioFormat::F64le,
            crate::AudioFormat::F64be,
            crate::AudioFormat::F32le,
            crate::AudioFormat::F32be,
            crate::AudioFormat::S32le,
            crate::AudioFormat::S32be,
            crate::AudioFormat::U32le,
            crate::AudioFormat::U32be,
            crate::AudioFormat::S2432le,
            crate::AudioFormat::S2432be,
            crate::AudioFormat::U2432le,
            crate::AudioFormat::U2432be,
            crate::AudioFormat::S24le,
            crate::AudioFormat::S24be,
            crate::AudioFormat::U24le,
            crate::AudioFormat::U24be,
            crate::AudioFormat::S20le,
            crate::AudioFormat::S20be,
            crate::AudioFormat::U20le,
            crate::AudioFormat::U20be,
            crate::AudioFormat::S18le,
            crate::AudioFormat::S18be,
            crate::AudioFormat::U18le,
            crate::AudioFormat::U18be,
            crate::AudioFormat::S16le,
            crate::AudioFormat::S16be,
            crate::AudioFormat::U16le,
            crate::AudioFormat::U16be,
            crate::AudioFormat::S8,
            crate::AudioFormat::U8,
        ])
    }
    #[cfg(target_endian = "big")]
    {
        Box::new([
            crate::AudioFormat::F64be,
            crate::AudioFormat::F64le,
            crate::AudioFormat::F32be,
            crate::AudioFormat::F32le,
            crate::AudioFormat::S32be,
            crate::AudioFormat::S32le,
            crate::AudioFormat::U32be,
            crate::AudioFormat::U32le,
            crate::AudioFormat::S2432be,
            crate::AudioFormat::S2432le,
            crate::AudioFormat::U2432be,
            crate::AudioFormat::U2432le,
            crate::AudioFormat::S24be,
            crate::AudioFormat::S24le,
            crate::AudioFormat::U24be,
            crate::AudioFormat::U24le,
            crate::AudioFormat::S20be,
            crate::AudioFormat::S20le,
            crate::AudioFormat::U20be,
            crate::AudioFormat::U20le,
            crate::AudioFormat::S18be,
            crate::AudioFormat::S18le,
            crate::AudioFormat::U18be,
            crate::AudioFormat::U18le,
            crate::AudioFormat::S16be,
            crate::AudioFormat::S16le,
            crate::AudioFormat::U16be,
            crate::AudioFormat::U16le,
            crate::AudioFormat::S8,
            crate::AudioFormat::U8,
        ])
    }
});

impl crate::AudioFormat {
    #[doc(alias = "gst_audio_format_build_integer")]
    pub fn build_integer(
        sign: bool,
        endianness: crate::AudioEndianness,
        width: i32,
        depth: i32,
    ) -> Self {
        assert_initialized_main_thread!();

        unsafe {
            from_glib(ffi::gst_audio_format_build_integer(
                sign.into_glib(),
                endianness.into_glib(),
                width,
                depth,
            ))
        }
    }

    #[doc(alias = "gst_audio_format_to_string")]
    pub fn to_str<'a>(self) -> &'a str {
        if self == Self::Unknown {
            return "UNKNOWN";
        }
        unsafe {
            CStr::from_ptr(
                ffi::gst_audio_format_to_string(self.into_glib())
                    .as_ref()
                    .expect("gst_audio_format_to_string returned NULL"),
            )
            .to_str()
            .expect("gst_audio_format_to_string returned an invalid string")
        }
    }

    pub fn iter_raw() -> AudioFormatIterator {
        AudioFormatIterator::default()
    }
}

impl str::FromStr for crate::AudioFormat {
    type Err = glib::BoolError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        skip_assert_initialized!();

        let fmt = Self::from_string(s);
        if fmt == Self::Unknown {
            Err(glib::bool_error!(
                "Failed to parse audio format from string"
            ))
        } else {
            Ok(fmt)
        }
    }
}

impl PartialOrd for crate::AudioFormat {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        crate::AudioFormatInfo::from_format(*self)
            .partial_cmp(&crate::AudioFormatInfo::from_format(*other))
    }
}

impl Ord for crate::AudioFormat {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        crate::AudioFormatInfo::from_format(*self).cmp(&crate::AudioFormatInfo::from_format(*other))
    }
}

pub const AUDIO_FORMAT_UNKNOWN: crate::AudioFormat = crate::AudioFormat::Unknown;
pub const AUDIO_FORMAT_ENCODED: crate::AudioFormat = crate::AudioFormat::Encoded;
pub const AUDIO_FORMAT_S8: crate::AudioFormat = crate::AudioFormat::S8;
pub const AUDIO_FORMAT_U8: crate::AudioFormat = crate::AudioFormat::U8;

#[cfg(target_endian = "big")]
pub const AUDIO_FORMAT_S16: crate::AudioFormat = crate::AudioFormat::S16be;
#[cfg(target_endian = "big")]
pub const AUDIO_FORMAT_U16: crate::AudioFormat = crate::AudioFormat::U16be;
#[cfg(target_endian = "big")]
pub const AUDIO_FORMAT_S2432: crate::AudioFormat = crate::AudioFormat::S2432be;
#[cfg(target_endian = "big")]
pub const AUDIO_FORMAT_U2432: crate::AudioFormat = crate::AudioFormat::U2432be;
#[cfg(target_endian = "big")]
pub const AUDIO_FORMAT_S32: crate::AudioFormat = crate::AudioFormat::S32be;
#[cfg(target_endian = "big")]
pub const AUDIO_FORMAT_U32: crate::AudioFormat = crate::AudioFormat::U32be;
#[cfg(target_endian = "big")]
pub const AUDIO_FORMAT_S24: crate::AudioFormat = crate::AudioFormat::S24be;
#[cfg(target_endian = "big")]
pub const AUDIO_FORMAT_U24: crate::AudioFormat = crate::AudioFormat::U24be;
#[cfg(target_endian = "big")]
pub const AUDIO_FORMAT_S20: crate::AudioFormat = crate::AudioFormat::S20be;
#[cfg(target_endian = "big")]
pub const AUDIO_FORMAT_U20: crate::AudioFormat = crate::AudioFormat::U20be;
#[cfg(target_endian = "big")]
pub const AUDIO_FORMAT_S18: crate::AudioFormat = crate::AudioFormat::S18be;
#[cfg(target_endian = "big")]
pub const AUDIO_FORMAT_U18: crate::AudioFormat = crate::AudioFormat::U18be;
#[cfg(target_endian = "big")]
pub const AUDIO_FORMAT_F32: crate::AudioFormat = crate::AudioFormat::F32be;
#[cfg(target_endian = "big")]
pub const AUDIO_FORMAT_F64: crate::AudioFormat = crate::AudioFormat::F64be;

#[cfg(target_endian = "little")]
pub const AUDIO_FORMAT_S16: crate::AudioFormat = crate::AudioFormat::S16le;
#[cfg(target_endian = "little")]
pub const AUDIO_FORMAT_U16: crate::AudioFormat = crate::AudioFormat::U16le;
#[cfg(target_endian = "little")]
pub const AUDIO_FORMAT_S2432: crate::AudioFormat = crate::AudioFormat::S2432le;
#[cfg(target_endian = "little")]
pub const AUDIO_FORMAT_U2432: crate::AudioFormat = crate::AudioFormat::U2432le;
#[cfg(target_endian = "little")]
pub const AUDIO_FORMAT_S32: crate::AudioFormat = crate::AudioFormat::S32le;
#[cfg(target_endian = "little")]
pub const AUDIO_FORMAT_U32: crate::AudioFormat = crate::AudioFormat::U32le;
#[cfg(target_endian = "little")]
pub const AUDIO_FORMAT_S24: crate::AudioFormat = crate::AudioFormat::S24le;
#[cfg(target_endian = "little")]
pub const AUDIO_FORMAT_U24: crate::AudioFormat = crate::AudioFormat::U24le;
#[cfg(target_endian = "little")]
pub const AUDIO_FORMAT_S20: crate::AudioFormat = crate::AudioFormat::S20le;
#[cfg(target_endian = "little")]
pub const AUDIO_FORMAT_U20: crate::AudioFormat = crate::AudioFormat::U20le;
#[cfg(target_endian = "little")]
pub const AUDIO_FORMAT_S18: crate::AudioFormat = crate::AudioFormat::S18le;
#[cfg(target_endian = "little")]
pub const AUDIO_FORMAT_U18: crate::AudioFormat = crate::AudioFormat::U18le;
#[cfg(target_endian = "little")]
pub const AUDIO_FORMAT_F32: crate::AudioFormat = crate::AudioFormat::F32le;
#[cfg(target_endian = "little")]
pub const AUDIO_FORMAT_F64: crate::AudioFormat = crate::AudioFormat::F64le;

pub struct AudioFormatIterator {
    idx: usize,
    len: usize,
}

impl Default for AudioFormatIterator {
    fn default() -> Self {
        Self {
            idx: 0,
            len: AUDIO_FORMATS_ALL.len(),
        }
    }
}

impl Iterator for AudioFormatIterator {
    type Item = crate::AudioFormat;

    fn next(&mut self) -> Option<Self::Item> {
        if self.idx >= self.len {
            None
        } else {
            let fmt = AUDIO_FORMATS_ALL[self.idx];
            self.idx += 1;
            Some(fmt)
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        if self.idx == self.len {
            return (0, Some(0));
        }

        let remaining = (self.len - self.idx) as usize;

        (remaining, Some(remaining))
    }
}

impl ExactSizeIterator for AudioFormatIterator {}

impl DoubleEndedIterator for AudioFormatIterator {
    fn next_back(&mut self) -> Option<Self::Item> {
        if self.idx >= self.len {
            None
        } else {
            let fmt = AUDIO_FORMATS_ALL[self.len - 1];
            self.len -= 1;
            Some(fmt)
        }
    }
}
pub trait AudioFormatIteratorExt {
    fn into_audio_caps(
        self,
        layout: crate::AudioLayout,
    ) -> Option<gst::caps::Builder<gst::caps::NoFeature>>;
}

impl<T> AudioFormatIteratorExt for T
where
    T: Iterator<Item = crate::AudioFormat>,
{
    fn into_audio_caps(
        self,
        layout: crate::AudioLayout,
    ) -> Option<gst::caps::Builder<gst::caps::NoFeature>> {
        let formats: Vec<crate::AudioFormat> = self.collect();
        if !formats.is_empty() {
            Some(crate::functions::audio_make_raw_caps(&formats, layout))
        } else {
            None
        }
    }
}

pub trait AudioFormatIteratorExtRef {
    fn into_audio_caps(
        self,
        layout: crate::AudioLayout,
    ) -> Option<gst::caps::Builder<gst::caps::NoFeature>>;
}

impl<'a, T> AudioFormatIteratorExtRef for T
where
    T: Iterator<Item = &'a crate::AudioFormat>,
{
    fn into_audio_caps(
        self,
        layout: crate::AudioLayout,
    ) -> Option<gst::caps::Builder<gst::caps::NoFeature>> {
        let formats: Vec<crate::AudioFormat> = self.copied().collect();
        if !formats.is_empty() {
            Some(crate::functions::audio_make_raw_caps(&formats, layout))
        } else {
            None
        }
    }
}

#[cfg(test)]
mod tests {
    use itertools::Itertools;

    #[test]
    fn test_display() {
        gst::init().unwrap();

        format!("{}", crate::AudioFormat::S16be);
    }

    #[test]
    fn iter() {
        use super::*;
        gst::init().unwrap();

        assert!(crate::AudioFormat::iter_raw().count() > 0);
        assert_eq!(
            crate::AudioFormat::iter_raw().count(),
            crate::AudioFormat::iter_raw().len()
        );

        let mut i = crate::AudioFormat::iter_raw();
        let mut count = 0;
        loop {
            if i.next().is_none() {
                break;
            }
            count += 1;
            if i.next_back().is_none() {
                break;
            }
            count += 1;
        }
        assert_eq!(count, crate::AudioFormat::iter_raw().len());

        assert!(crate::AudioFormat::iter_raw().any(|f| f == crate::AudioFormat::F64be));
        assert!(!crate::AudioFormat::iter_raw().any(|f| f == crate::AudioFormat::Encoded));

        let caps = crate::AudioFormat::iter_raw().into_audio_caps(crate::AudioLayout::Interleaved);
        assert!(caps.is_some());

        let caps = crate::AudioFormat::iter_raw()
            .filter(|f| crate::AudioFormatInfo::from_format(*f).is_little_endian())
            .into_audio_caps(crate::AudioLayout::Interleaved);
        assert!(caps.is_some());

        let caps = crate::AudioFormat::iter_raw()
            .skip(1000)
            .into_audio_caps(crate::AudioLayout::Interleaved);
        assert!(caps.is_none());

        let caps = [crate::AudioFormat::S16le, crate::AudioFormat::S16be]
            .iter()
            .into_audio_caps(crate::AudioLayout::Interleaved)
            .unwrap()
            .build();
        assert_eq!(caps.to_string(), "audio/x-raw, format=(string){ S16LE, S16BE }, rate=(int)[ 1, 2147483647 ], channels=(int)[ 1, 2147483647 ], layout=(string)interleaved");
    }

    #[test]
    fn sort() {
        gst::init().unwrap();

        assert!(
            crate::AudioFormatInfo::from_format(crate::AudioFormat::F64be)
                > crate::AudioFormatInfo::from_format(crate::AudioFormat::U8)
        );
        assert!(crate::AudioFormat::S20be > crate::AudioFormat::S18be);

        let sorted: Vec<crate::AudioFormat> =
            crate::AudioFormat::iter_raw().sorted().rev().collect();
        // FIXME: use is_sorted_by() once API is in stable
        assert_eq!(
            sorted,
            crate::AudioFormat::iter_raw().collect::<Vec<crate::AudioFormat>>()
        );
    }
}