1use thiserror::Error;
2
3#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
5pub enum FormatValidationError {
6 #[error("stream format size must be positive, got {width}x{height}")]
7 ZeroSize { width: u32, height: u32 },
8 #[error("stream framerate must be positive, got {numerator}/{denominator}")]
9 InvalidFramerate { numerator: u32, denominator: u32 },
10 #[error("stream format has invalid DRM fourcc 0")]
11 InvalidFourcc,
12 #[error("BW1 binary format requires a polarity")]
13 MissingBw1Polarity,
14 #[error("BW1 polarity is only valid for BW1 binary format")]
15 UnexpectedBw1Polarity,
16 #[error("binary storage format requires implicit synchronization")]
17 BinaryFormatRequiresImplicitSync,
18 #[error("binary formats without alpha require opaque alpha mode")]
19 BinaryFormatRequiresOpaqueAlpha,
20 #[error("pixel aspect ratio must be positive, got {numerator}/{denominator}")]
21 InvalidPixelAspectRatio { numerator: u32, denominator: u32 },
22}
23
24pub type Rational = (u32, u32);
26
27#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
29#[cfg_attr(feature = "rustler", derive(rustler::NifUnitEnum))]
30pub enum AcquireSyncPolicy {
31 Implicit,
32 SyncFile,
33 PerFrame,
34}
35
36#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
38pub enum ModifierPolicy {
39 PerBuffer,
40 Implicit,
41 Explicit(u64),
42}
43
44pub type StreamAcquireSyncPolicy = AcquireSyncPolicy;
46pub type StreamModifierPolicy = ModifierPolicy;
48
49#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
50#[cfg_attr(feature = "rustler", derive(rustler::NifUnitEnum))]
51pub enum Primaries {
52 Unspecified,
53 Bt709,
54 Bt470M,
55 Bt470Bg,
56 Smpte170m,
57 Smpte240m,
58 Film,
59 Bt2020,
60 Smpte428,
61 Smpte431,
62 Smpte432,
63 Ebu3213,
64}
65
66#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
67#[cfg_attr(feature = "rustler", derive(rustler::NifUnitEnum))]
68pub enum Transfer {
69 Unspecified,
70 Bt709,
71 Gamma22,
72 Gamma28,
73 Smpte170m,
74 Smpte240m,
75 Linear,
76 Log,
77 LogSqrt,
78 Iec61966_2_4,
79 Bt1361,
80 Iec61966_2_1,
81 Bt2020_10,
82 Bt2020_12,
83 Smpte2084,
84 Smpte428,
85 AribStdB67,
86}
87
88#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
89#[cfg_attr(feature = "rustler", derive(rustler::NifUnitEnum))]
90pub enum Matrix {
91 Unspecified,
92 Rgb,
93 Bt709,
94 Fcc,
95 Bt470Bg,
96 Smpte170m,
97 Smpte240m,
98 Ycgco,
99 Bt2020Ncl,
100 Bt2020Cl,
101 Smpte2085,
102 ChromaDerivedNcl,
103 ChromaDerivedCl,
104 Ictcp,
105}
106
107#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
108#[cfg_attr(feature = "rustler", derive(rustler::NifUnitEnum))]
109pub enum ColorRange {
110 Unspecified,
111 Limited,
112 Full,
113}
114
115#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
116#[cfg_attr(feature = "rustler", derive(rustler::NifUnitEnum))]
117pub enum ChromaLocation {
118 Unspecified,
119 Left,
120 Center,
121 TopLeft,
122 Top,
123 BottomLeft,
124 Bottom,
125}
126
127#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
128#[cfg_attr(feature = "rustler", derive(rustler::NifUnitEnum))]
129pub enum InterlaceMode {
130 Progressive,
131 InterlacedTopFirst,
132 InterlacedBottomFirst,
133 Mixed,
134}
135
136#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
137#[cfg_attr(feature = "rustler", derive(rustler::NifUnitEnum))]
138pub enum AlphaMode {
139 Opaque,
140 Straight,
141 Premultiplied,
142}
143
144#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
146#[cfg_attr(feature = "rustler", derive(rustler::NifStruct))]
147#[cfg_attr(feature = "rustler", module = "VideoInterop.Colorimetry")]
148pub struct Colorimetry {
149 pub primaries: Primaries,
150 pub transfer: Transfer,
151 pub matrix: Matrix,
152 pub range: ColorRange,
153 pub chroma_location: ChromaLocation,
154}
155
156impl Default for Colorimetry {
157 fn default() -> Self {
158 Self {
159 primaries: Primaries::Unspecified,
160 transfer: Transfer::Unspecified,
161 matrix: Matrix::Unspecified,
162 range: ColorRange::Unspecified,
163 chroma_location: ChromaLocation::Unspecified,
164 }
165 }
166}
167
168#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
169#[cfg_attr(feature = "rustler", derive(rustler::NifUnitEnum))]
170pub enum BinaryPixelFormat {
171 Rgba8888,
172 Bgra8888,
174 Rgb888,
175 Gray8,
176 Gray2,
177 Bw1,
178}
179
180#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
181#[cfg_attr(feature = "rustler", derive(rustler::NifUnitEnum))]
182pub enum Bw1Polarity {
183 OneIsBlack,
184 OneIsWhite,
185}
186
187#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
189#[cfg_attr(feature = "rustler", derive(rustler::NifStruct))]
190#[cfg_attr(feature = "rustler", module = "VideoInterop.Binary.Format")]
191pub struct BinaryFormat {
192 pub pixel_format: BinaryPixelFormat,
193 pub bw1_polarity: Option<Bw1Polarity>,
194}
195
196impl BinaryFormat {
197 pub fn validate(&self) -> Result<(), FormatValidationError> {
198 match (self.pixel_format, self.bw1_polarity) {
199 (BinaryPixelFormat::Bw1, None) => Err(FormatValidationError::MissingBw1Polarity),
200 (BinaryPixelFormat::Bw1, Some(_)) | (_, None) => Ok(()),
201 (_, Some(_)) => Err(FormatValidationError::UnexpectedBw1Polarity),
202 }
203 }
204}
205
206#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
208#[cfg_attr(feature = "rustler", derive(rustler::NifStruct))]
209#[cfg_attr(feature = "rustler", module = "VideoInterop.DMABuf.Format")]
210pub struct DmaBufFormat {
211 pub fourcc: u32,
212 pub modifier: ModifierPolicy,
213}
214
215impl DmaBufFormat {
216 pub fn validate(&self) -> Result<(), FormatValidationError> {
217 if self.fourcc == 0 {
218 return Err(FormatValidationError::InvalidFourcc);
219 }
220 Ok(())
221 }
222}
223
224#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
225pub enum StorageFormat {
226 Binary(BinaryFormat),
227 DmaBuf(DmaBufFormat),
228}
229
230impl StorageFormat {
231 pub fn validate(&self) -> Result<(), FormatValidationError> {
232 match self {
233 Self::Binary(format) => format.validate(),
234 Self::DmaBuf(format) => format.validate(),
235 }
236 }
237}
238
239#[derive(Clone, Debug, Eq, Hash, PartialEq)]
241#[cfg_attr(feature = "rustler", derive(rustler::NifStruct))]
242#[cfg_attr(feature = "rustler", module = "VideoInterop.Format")]
243pub struct Format {
244 pub width: u32,
245 pub height: u32,
246 pub framerate: Option<Rational>,
247 pub storage: StorageFormat,
248 pub acquire_sync: AcquireSyncPolicy,
249 pub colorimetry: Colorimetry,
250 pub pixel_aspect_ratio: Rational,
251 pub interlace_mode: InterlaceMode,
252 pub alpha_mode: AlphaMode,
253}
254
255impl Format {
256 pub fn validate(&self) -> Result<(), FormatValidationError> {
260 if self.width == 0 || self.height == 0 {
261 return Err(FormatValidationError::ZeroSize {
262 width: self.width,
263 height: self.height,
264 });
265 }
266
267 if let Some((numerator, denominator)) = self.framerate
268 && (numerator == 0 || denominator == 0)
269 {
270 return Err(FormatValidationError::InvalidFramerate {
271 numerator,
272 denominator,
273 });
274 }
275
276 self.storage.validate()?;
277 if let StorageFormat::Binary(storage) = self.storage {
278 if self.acquire_sync != AcquireSyncPolicy::Implicit {
279 return Err(FormatValidationError::BinaryFormatRequiresImplicitSync);
280 }
281 if !matches!(
282 storage.pixel_format,
283 BinaryPixelFormat::Rgba8888 | BinaryPixelFormat::Bgra8888
284 ) && self.alpha_mode != AlphaMode::Opaque
285 {
286 return Err(FormatValidationError::BinaryFormatRequiresOpaqueAlpha);
287 }
288 }
289
290 let (numerator, denominator) = self.pixel_aspect_ratio;
291 if numerator == 0 || denominator == 0 {
292 return Err(FormatValidationError::InvalidPixelAspectRatio {
293 numerator,
294 denominator,
295 });
296 }
297
298 Ok(())
299 }
300}
301
302#[cfg(feature = "rustler")]
303mod rustler_impl {
304 use rustler::{Decoder, Encoder, Env, Error, NifResult, Term};
305
306 use super::{BinaryFormat, DmaBufFormat, ModifierPolicy, StorageFormat};
307
308 mod atoms {
309 rustler::atoms! {
310 per_buffer,
311 implicit
312 }
313 }
314
315 impl<'a> Decoder<'a> for ModifierPolicy {
316 fn decode(term: Term<'a>) -> NifResult<Self> {
317 if let Ok(atom) = term.decode::<rustler::Atom>() {
318 if atom == atoms::per_buffer() {
319 return Ok(Self::PerBuffer);
320 }
321 if atom == atoms::implicit() {
322 return Ok(Self::Implicit);
323 }
324 return Err(Error::BadArg);
325 }
326
327 term.decode::<u64>().map(Self::Explicit)
328 }
329 }
330
331 impl<'a> Decoder<'a> for StorageFormat {
332 fn decode(term: Term<'a>) -> NifResult<Self> {
333 if let Ok(format) = term.decode::<DmaBufFormat>() {
334 return Ok(Self::DmaBuf(format));
335 }
336 term.decode::<BinaryFormat>().map(Self::Binary)
337 }
338 }
339
340 impl Encoder for StorageFormat {
341 fn encode<'a>(&self, env: Env<'a>) -> Term<'a> {
342 match self {
343 Self::Binary(format) => format.encode(env),
344 Self::DmaBuf(format) => format.encode(env),
345 }
346 }
347 }
348
349 impl Encoder for ModifierPolicy {
350 fn encode<'a>(&self, env: Env<'a>) -> Term<'a> {
351 match self {
352 Self::PerBuffer => atoms::per_buffer().encode(env),
353 Self::Implicit => atoms::implicit().encode(env),
354 Self::Explicit(value) => value.encode(env),
355 }
356 }
357 }
358}
359
360#[cfg(test)]
361mod tests {
362 use super::*;
363
364 fn format() -> Format {
365 Format {
366 width: 640,
367 height: 480,
368 framerate: Some((60, 1)),
369 storage: StorageFormat::DmaBuf(DmaBufFormat {
370 fourcc: u32::from_le_bytes(*b"NV12"),
371 modifier: ModifierPolicy::PerBuffer,
372 }),
373 acquire_sync: AcquireSyncPolicy::PerFrame,
374 colorimetry: Colorimetry::default(),
375 pixel_aspect_ratio: (1, 1),
376 interlace_mode: InterlaceMode::Progressive,
377 alpha_mode: AlphaMode::Opaque,
378 }
379 }
380
381 #[test]
382 fn validates_supported_stream_policy_values() {
383 for modifier in [
384 ModifierPolicy::PerBuffer,
385 ModifierPolicy::Implicit,
386 ModifierPolicy::Explicit(0),
387 ModifierPolicy::Explicit(u64::MAX),
388 ] {
389 for acquire_sync in [
390 AcquireSyncPolicy::Implicit,
391 AcquireSyncPolicy::SyncFile,
392 AcquireSyncPolicy::PerFrame,
393 ] {
394 let mut candidate = format();
395 let StorageFormat::DmaBuf(storage) = &mut candidate.storage else {
396 unreachable!()
397 };
398 storage.modifier = modifier;
399 candidate.acquire_sync = acquire_sync;
400 assert_eq!(candidate.validate(), Ok(()));
401 }
402 }
403 }
404
405 #[test]
406 fn binary_formats_require_implicit_synchronization() {
407 let mut candidate = format();
408 candidate.storage = StorageFormat::Binary(BinaryFormat {
409 pixel_format: BinaryPixelFormat::Gray8,
410 bw1_polarity: None,
411 });
412 assert_eq!(
413 candidate.validate(),
414 Err(FormatValidationError::BinaryFormatRequiresImplicitSync)
415 );
416 candidate.acquire_sync = AcquireSyncPolicy::Implicit;
417 assert_eq!(candidate.validate(), Ok(()));
418 candidate.alpha_mode = AlphaMode::Straight;
419 assert_eq!(
420 candidate.validate(),
421 Err(FormatValidationError::BinaryFormatRequiresOpaqueAlpha)
422 );
423 }
424
425 #[test]
426 fn default_colorimetry_is_explicitly_unspecified() {
427 assert_eq!(
428 Colorimetry::default(),
429 Colorimetry {
430 primaries: Primaries::Unspecified,
431 transfer: Transfer::Unspecified,
432 matrix: Matrix::Unspecified,
433 range: ColorRange::Unspecified,
434 chroma_location: ChromaLocation::Unspecified,
435 }
436 );
437 }
438
439 #[test]
440 fn represents_every_elixir_colorimetry_value() {
441 let primaries = [
442 Primaries::Unspecified,
443 Primaries::Bt709,
444 Primaries::Bt470M,
445 Primaries::Bt470Bg,
446 Primaries::Smpte170m,
447 Primaries::Smpte240m,
448 Primaries::Film,
449 Primaries::Bt2020,
450 Primaries::Smpte428,
451 Primaries::Smpte431,
452 Primaries::Smpte432,
453 Primaries::Ebu3213,
454 ];
455 let transfers = [
456 Transfer::Unspecified,
457 Transfer::Bt709,
458 Transfer::Gamma22,
459 Transfer::Gamma28,
460 Transfer::Smpte170m,
461 Transfer::Smpte240m,
462 Transfer::Linear,
463 Transfer::Log,
464 Transfer::LogSqrt,
465 Transfer::Iec61966_2_4,
466 Transfer::Bt1361,
467 Transfer::Iec61966_2_1,
468 Transfer::Bt2020_10,
469 Transfer::Bt2020_12,
470 Transfer::Smpte2084,
471 Transfer::Smpte428,
472 Transfer::AribStdB67,
473 ];
474 let matrices = [
475 Matrix::Unspecified,
476 Matrix::Rgb,
477 Matrix::Bt709,
478 Matrix::Fcc,
479 Matrix::Bt470Bg,
480 Matrix::Smpte170m,
481 Matrix::Smpte240m,
482 Matrix::Ycgco,
483 Matrix::Bt2020Ncl,
484 Matrix::Bt2020Cl,
485 Matrix::Smpte2085,
486 Matrix::ChromaDerivedNcl,
487 Matrix::ChromaDerivedCl,
488 Matrix::Ictcp,
489 ];
490 let ranges = [
491 ColorRange::Unspecified,
492 ColorRange::Limited,
493 ColorRange::Full,
494 ];
495 let chroma_locations = [
496 ChromaLocation::Unspecified,
497 ChromaLocation::Left,
498 ChromaLocation::Center,
499 ChromaLocation::TopLeft,
500 ChromaLocation::Top,
501 ChromaLocation::BottomLeft,
502 ChromaLocation::Bottom,
503 ];
504
505 assert_eq!(primaries.len(), 12);
506 assert_eq!(transfers.len(), 17);
507 assert_eq!(matrices.len(), 14);
508 assert_eq!(ranges.len(), 3);
509 assert_eq!(chroma_locations.len(), 7);
510 }
511
512 #[test]
513 fn rejects_invalid_numeric_schema_values() {
514 let mut candidate = format();
515 candidate.width = 0;
516 assert_eq!(
517 candidate.validate(),
518 Err(FormatValidationError::ZeroSize {
519 width: 0,
520 height: 480
521 })
522 );
523
524 let mut candidate = format();
525 candidate.framerate = Some((60, 0));
526 assert_eq!(
527 candidate.validate(),
528 Err(FormatValidationError::InvalidFramerate {
529 numerator: 60,
530 denominator: 0
531 })
532 );
533
534 let mut candidate = format();
535 let StorageFormat::DmaBuf(storage) = &mut candidate.storage else {
536 unreachable!()
537 };
538 storage.fourcc = 0;
539 assert_eq!(
540 candidate.validate(),
541 Err(FormatValidationError::InvalidFourcc)
542 );
543
544 let mut candidate = format();
545 candidate.pixel_aspect_ratio = (0, 1);
546 assert_eq!(
547 candidate.validate(),
548 Err(FormatValidationError::InvalidPixelAspectRatio {
549 numerator: 0,
550 denominator: 1
551 })
552 );
553 }
554}