ff-format 0.14.2

Common types for video/audio processing - the Rust way
Documentation
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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
//! [`Rational`] number type for representing fractions.

// These casts are intentional for media timestamp arithmetic.
// The values involved (PTS, time bases, frame rates) are well within
// the safe ranges for these conversions in practical video/audio scenarios.
#![allow(
    clippy::cast_possible_truncation,
    clippy::cast_possible_wrap,
    clippy::cast_precision_loss,
    clippy::cast_sign_loss
)]

use std::cmp::Ordering;
use std::fmt;
use std::ops::{Add, Div, Mul, Neg, Sub};

/// A rational number represented as a fraction (numerator / denominator).
///
/// This type is commonly used to represent:
/// - Time bases (e.g., 1/90000 for MPEG-TS, 1/1000 for milliseconds)
/// - Frame rates (e.g., 30000/1001 for 29.97 fps)
/// - Aspect ratios (e.g., 16/9)
///
/// # Invariants
///
/// - Denominator is always positive (sign is in numerator)
/// - Zero denominator is handled gracefully (returns infinity/NaN for conversions)
///
/// # Examples
///
/// ```
/// use ff_format::Rational;
///
/// // Common time base for MPEG-TS
/// let time_base = Rational::new(1, 90000);
///
/// // 29.97 fps (NTSC)
/// let fps = Rational::new(30000, 1001);
/// assert!((fps.as_f64() - 29.97).abs() < 0.01);
///
/// // Invert to get frame duration
/// let frame_duration = fps.invert();
/// assert_eq!(frame_duration.num(), 1001);
/// assert_eq!(frame_duration.den(), 30000);
/// ```
#[derive(Debug, Clone, Copy)]
pub struct Rational {
    num: i32,
    den: i32,
}

impl PartialEq for Rational {
    fn eq(&self, other: &Self) -> bool {
        // a/b == c/d iff a*d == b*c (cross-multiplication)
        // Use i64 to avoid overflow
        i64::from(self.num) * i64::from(other.den) == i64::from(other.num) * i64::from(self.den)
    }
}

impl Eq for Rational {}

impl std::hash::Hash for Rational {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        // Hash the reduced form to ensure equal values have equal hashes
        let reduced = self.reduce();
        reduced.num.hash(state);
        reduced.den.hash(state);
    }
}

impl Rational {
    /// Creates a new rational number.
    ///
    /// The denominator is normalized to always be positive (the sign is moved
    /// to the numerator).
    ///
    /// # Panics
    ///
    /// Does not panic. A zero denominator is allowed but will result in
    /// infinity or NaN when converted to floating-point.
    ///
    /// # Examples
    ///
    /// ```
    /// use ff_format::Rational;
    ///
    /// let r = Rational::new(1, 2);
    /// assert_eq!(r.num(), 1);
    /// assert_eq!(r.den(), 2);
    ///
    /// // Negative denominator is normalized
    /// let r = Rational::new(1, -2);
    /// assert_eq!(r.num(), -1);
    /// assert_eq!(r.den(), 2);
    /// ```
    #[must_use]
    pub const fn new(num: i32, den: i32) -> Self {
        // Normalize: denominator should always be positive
        if den < 0 {
            Self {
                num: -num,
                den: -den,
            }
        } else {
            Self { num, den }
        }
    }

    /// Creates a rational number representing zero (0/1).
    ///
    /// # Examples
    ///
    /// ```
    /// use ff_format::Rational;
    ///
    /// let zero = Rational::zero();
    /// assert_eq!(zero.as_f64(), 0.0);
    /// assert!(zero.is_zero());
    /// ```
    #[must_use]
    pub const fn zero() -> Self {
        Self { num: 0, den: 1 }
    }

    /// Creates a rational number representing one (1/1).
    ///
    /// # Examples
    ///
    /// ```
    /// use ff_format::Rational;
    ///
    /// let one = Rational::one();
    /// assert_eq!(one.as_f64(), 1.0);
    /// ```
    #[must_use]
    pub const fn one() -> Self {
        Self { num: 1, den: 1 }
    }

    /// Returns the numerator.
    ///
    /// # Examples
    ///
    /// ```
    /// use ff_format::Rational;
    ///
    /// let r = Rational::new(3, 4);
    /// assert_eq!(r.num(), 3);
    /// ```
    #[must_use]
    #[inline]
    pub const fn num(&self) -> i32 {
        self.num
    }

    /// Returns the denominator.
    ///
    /// The denominator is always non-negative.
    ///
    /// # Examples
    ///
    /// ```
    /// use ff_format::Rational;
    ///
    /// let r = Rational::new(3, 4);
    /// assert_eq!(r.den(), 4);
    /// ```
    #[must_use]
    #[inline]
    pub const fn den(&self) -> i32 {
        self.den
    }

    /// Converts the rational number to a floating-point value.
    ///
    /// Returns `f64::INFINITY`, `f64::NEG_INFINITY`, or `f64::NAN` for
    /// edge cases (division by zero).
    ///
    /// # Examples
    ///
    /// ```
    /// use ff_format::Rational;
    ///
    /// let r = Rational::new(1, 4);
    /// assert_eq!(r.as_f64(), 0.25);
    ///
    /// let r = Rational::new(1, 3);
    /// assert!((r.as_f64() - 0.333333).abs() < 0.001);
    /// ```
    #[must_use]
    #[inline]
    pub fn as_f64(self) -> f64 {
        if self.den == 0 {
            match self.num.cmp(&0) {
                Ordering::Greater => f64::INFINITY,
                Ordering::Less => f64::NEG_INFINITY,
                Ordering::Equal => f64::NAN,
            }
        } else {
            f64::from(self.num) / f64::from(self.den)
        }
    }

    /// Converts the rational number to a single-precision floating-point value.
    ///
    /// # Examples
    ///
    /// ```
    /// use ff_format::Rational;
    ///
    /// let r = Rational::new(1, 2);
    /// assert_eq!(r.as_f32(), 0.5);
    /// ```
    #[must_use]
    #[inline]
    pub fn as_f32(self) -> f32 {
        self.as_f64() as f32
    }

    /// Returns the inverse (reciprocal) of this rational number.
    ///
    /// # Examples
    ///
    /// ```
    /// use ff_format::Rational;
    ///
    /// let r = Rational::new(3, 4);
    /// let inv = r.invert();
    /// assert_eq!(inv.num(), 4);
    /// assert_eq!(inv.den(), 3);
    ///
    /// // Negative values
    /// let r = Rational::new(-3, 4);
    /// let inv = r.invert();
    /// assert_eq!(inv.num(), -4);
    /// assert_eq!(inv.den(), 3);
    /// ```
    #[must_use]
    pub const fn invert(self) -> Self {
        // Handle sign normalization when inverting
        if self.num < 0 {
            Self {
                num: -self.den,
                den: -self.num,
            }
        } else {
            Self {
                num: self.den,
                den: self.num,
            }
        }
    }

    /// Returns true if this rational number is zero.
    ///
    /// # Examples
    ///
    /// ```
    /// use ff_format::Rational;
    ///
    /// assert!(Rational::new(0, 1).is_zero());
    /// assert!(Rational::new(0, 100).is_zero());
    /// assert!(!Rational::new(1, 100).is_zero());
    /// ```
    #[must_use]
    #[inline]
    pub const fn is_zero(self) -> bool {
        self.num == 0
    }

    /// Returns true if this rational number is positive.
    ///
    /// # Examples
    ///
    /// ```
    /// use ff_format::Rational;
    ///
    /// assert!(Rational::new(1, 2).is_positive());
    /// assert!(!Rational::new(-1, 2).is_positive());
    /// assert!(!Rational::new(0, 1).is_positive());
    /// ```
    #[must_use]
    #[inline]
    pub const fn is_positive(self) -> bool {
        self.num > 0 && self.den > 0
    }

    /// Returns true if this rational number is negative.
    ///
    /// # Examples
    ///
    /// ```
    /// use ff_format::Rational;
    ///
    /// assert!(Rational::new(-1, 2).is_negative());
    /// assert!(!Rational::new(1, 2).is_negative());
    /// assert!(!Rational::new(0, 1).is_negative());
    /// ```
    #[must_use]
    #[inline]
    pub const fn is_negative(self) -> bool {
        self.num < 0 && self.den > 0
    }

    /// Returns the absolute value of this rational number.
    ///
    /// # Examples
    ///
    /// ```
    /// use ff_format::Rational;
    ///
    /// assert_eq!(Rational::new(-3, 4).abs(), Rational::new(3, 4));
    /// assert_eq!(Rational::new(3, 4).abs(), Rational::new(3, 4));
    /// ```
    #[must_use]
    pub const fn abs(self) -> Self {
        Self {
            num: if self.num < 0 { -self.num } else { self.num },
            den: self.den,
        }
    }

    /// Reduces the rational to its lowest terms using GCD.
    ///
    /// # Examples
    ///
    /// ```
    /// use ff_format::Rational;
    ///
    /// let r = Rational::new(4, 8);
    /// let reduced = r.reduce();
    /// assert_eq!(reduced.num(), 1);
    /// assert_eq!(reduced.den(), 2);
    /// ```
    #[must_use]
    pub fn reduce(self) -> Self {
        if self.num == 0 {
            return Self::new(0, 1);
        }
        let g = gcd(self.num.unsigned_abs(), self.den.unsigned_abs());
        Self {
            num: self.num / g as i32,
            den: self.den / g as i32,
        }
    }
}

/// Computes the greatest common divisor using Euclidean algorithm.
fn gcd(mut a: u32, mut b: u32) -> u32 {
    while b != 0 {
        let temp = b;
        b = a % b;
        a = temp;
    }
    a
}

impl Default for Rational {
    /// Returns the default rational number (1/1).
    fn default() -> Self {
        Self::one()
    }
}

impl fmt::Display for Rational {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}/{}", self.num, self.den)
    }
}

impl From<i32> for Rational {
    fn from(n: i32) -> Self {
        Self::new(n, 1)
    }
}

impl From<(i32, i32)> for Rational {
    fn from((num, den): (i32, i32)) -> Self {
        Self::new(num, den)
    }
}

// Arithmetic operations for Rational

impl Add for Rational {
    type Output = Self;

    fn add(self, rhs: Self) -> Self::Output {
        // a/b + c/d = (ad + bc) / bd
        let num =
            i64::from(self.num) * i64::from(rhs.den) + i64::from(rhs.num) * i64::from(self.den);
        let den = i64::from(self.den) * i64::from(rhs.den);

        // Try to reduce to fit in i32
        let g = gcd(num.unsigned_abs() as u32, den.unsigned_abs() as u32);
        Self::new((num / i64::from(g)) as i32, (den / i64::from(g)) as i32)
    }
}

impl Sub for Rational {
    type Output = Self;

    fn sub(self, rhs: Self) -> Self::Output {
        // a/b - c/d = (ad - bc) / bd
        let num =
            i64::from(self.num) * i64::from(rhs.den) - i64::from(rhs.num) * i64::from(self.den);
        let den = i64::from(self.den) * i64::from(rhs.den);

        let g = gcd(num.unsigned_abs() as u32, den.unsigned_abs() as u32);
        Self::new((num / i64::from(g)) as i32, (den / i64::from(g)) as i32)
    }
}

impl Mul for Rational {
    type Output = Self;

    fn mul(self, rhs: Self) -> Self::Output {
        // a/b * c/d = ac / bd
        let num = i64::from(self.num) * i64::from(rhs.num);
        let den = i64::from(self.den) * i64::from(rhs.den);

        let g = gcd(num.unsigned_abs() as u32, den.unsigned_abs() as u32);
        Self::new((num / i64::from(g)) as i32, (den / i64::from(g)) as i32)
    }
}

impl Div for Rational {
    type Output = Self;

    #[allow(clippy::suspicious_arithmetic_impl)]
    fn div(self, rhs: Self) -> Self::Output {
        // a/b / c/d = a/b * d/c = ad / bc
        // Using multiplication by inverse is mathematically correct for rational division
        self * rhs.invert()
    }
}

impl Mul<i32> for Rational {
    type Output = Self;

    fn mul(self, rhs: i32) -> Self::Output {
        let num = i64::from(self.num) * i64::from(rhs);
        let g = gcd(num.unsigned_abs() as u32, self.den.unsigned_abs());
        Self::new((num / i64::from(g)) as i32, self.den / g as i32)
    }
}

impl Div<i32> for Rational {
    type Output = Self;

    fn div(self, rhs: i32) -> Self::Output {
        let den = i64::from(self.den) * i64::from(rhs);
        let g = gcd(self.num.unsigned_abs(), den.unsigned_abs() as u32);
        Self::new(self.num / g as i32, (den / i64::from(g)) as i32)
    }
}

impl Neg for Rational {
    type Output = Self;

    fn neg(self) -> Self::Output {
        Self::new(-self.num, self.den)
    }
}

impl PartialOrd for Rational {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Rational {
    fn cmp(&self, other: &Self) -> Ordering {
        // Compare a/b with c/d by comparing ad with bc
        let left = i64::from(self.num) * i64::from(other.den);
        let right = i64::from(other.num) * i64::from(self.den);
        left.cmp(&right)
    }
}

#[cfg(test)]
#[allow(
    clippy::unwrap_used,
    clippy::float_cmp,
    clippy::similar_names,
    clippy::redundant_closure_for_method_calls
)]
mod tests {
    use super::*;

    /// Helper for approximate float comparison in tests
    fn approx_eq(a: f64, b: f64) -> bool {
        (a - b).abs() < 1e-9
    }

    mod rational_tests {
        use super::*;

        #[test]
        fn test_new() {
            let r = Rational::new(1, 2);
            assert_eq!(r.num(), 1);
            assert_eq!(r.den(), 2);
        }

        #[test]
        fn test_new_negative_denominator() {
            // Negative denominator should be normalized
            let r = Rational::new(1, -2);
            assert_eq!(r.num(), -1);
            assert_eq!(r.den(), 2);

            let r = Rational::new(-1, -2);
            assert_eq!(r.num(), 1);
            assert_eq!(r.den(), 2);
        }

        #[test]
        fn test_zero_and_one() {
            let zero = Rational::zero();
            assert!(zero.is_zero());
            assert!(approx_eq(zero.as_f64(), 0.0));

            let one = Rational::one();
            assert!(approx_eq(one.as_f64(), 1.0));
            assert!(!one.is_zero());
        }

        #[test]
        fn test_as_f64() {
            assert!(approx_eq(Rational::new(1, 2).as_f64(), 0.5));
            assert!(approx_eq(Rational::new(1, 4).as_f64(), 0.25));
            assert!((Rational::new(1, 3).as_f64() - 0.333_333).abs() < 0.001);
            assert!(approx_eq(Rational::new(-1, 2).as_f64(), -0.5));
        }

        #[test]
        fn test_as_f64_division_by_zero() {
            assert!(Rational::new(1, 0).as_f64().is_infinite());
            assert!(Rational::new(1, 0).as_f64().is_sign_positive());
            assert!(Rational::new(-1, 0).as_f64().is_infinite());
            assert!(Rational::new(-1, 0).as_f64().is_sign_negative());
            assert!(Rational::new(0, 0).as_f64().is_nan());
        }

        #[test]
        fn test_as_f32() {
            assert_eq!(Rational::new(1, 2).as_f32(), 0.5);
        }

        #[test]
        fn test_invert() {
            let r = Rational::new(3, 4);
            let inv = r.invert();
            assert_eq!(inv.num(), 4);
            assert_eq!(inv.den(), 3);

            // Negative value
            let r = Rational::new(-3, 4);
            let inv = r.invert();
            assert_eq!(inv.num(), -4);
            assert_eq!(inv.den(), 3);
        }

        #[test]
        fn test_is_positive_negative() {
            assert!(Rational::new(1, 2).is_positive());
            assert!(!Rational::new(-1, 2).is_positive());
            assert!(!Rational::new(0, 1).is_positive());

            assert!(Rational::new(-1, 2).is_negative());
            assert!(!Rational::new(1, 2).is_negative());
            assert!(!Rational::new(0, 1).is_negative());
        }

        #[test]
        fn test_abs() {
            assert_eq!(Rational::new(-3, 4).abs(), Rational::new(3, 4));
            assert_eq!(Rational::new(3, 4).abs(), Rational::new(3, 4));
            assert_eq!(Rational::new(0, 4).abs(), Rational::new(0, 4));
        }

        #[test]
        fn test_reduce() {
            let r = Rational::new(4, 8);
            let reduced = r.reduce();
            assert_eq!(reduced.num(), 1);
            assert_eq!(reduced.den(), 2);

            let r = Rational::new(6, 9);
            let reduced = r.reduce();
            assert_eq!(reduced.num(), 2);
            assert_eq!(reduced.den(), 3);

            let r = Rational::new(0, 5);
            let reduced = r.reduce();
            assert_eq!(reduced.num(), 0);
            assert_eq!(reduced.den(), 1);
        }

        #[test]
        fn test_add() {
            let a = Rational::new(1, 2);
            let b = Rational::new(1, 4);
            let result = a + b;
            assert!((result.as_f64() - 0.75).abs() < 0.0001);
        }

        #[test]
        fn test_sub() {
            let a = Rational::new(1, 2);
            let b = Rational::new(1, 4);
            let result = a - b;
            assert!((result.as_f64() - 0.25).abs() < 0.0001);
        }

        #[test]
        fn test_mul() {
            let a = Rational::new(1, 2);
            let b = Rational::new(2, 3);
            let result = a * b;
            assert!((result.as_f64() - (1.0 / 3.0)).abs() < 0.0001);
        }

        #[test]
        fn test_div() {
            let a = Rational::new(1, 2);
            let b = Rational::new(2, 3);
            let result = a / b;
            assert!((result.as_f64() - 0.75).abs() < 0.0001);
        }

        #[test]
        fn test_mul_i32() {
            let r = Rational::new(1, 4);
            let result = r * 2;
            assert!((result.as_f64() - 0.5).abs() < 0.0001);
        }

        #[test]
        fn test_div_i32() {
            let r = Rational::new(1, 2);
            let result = r / 2;
            assert!((result.as_f64() - 0.25).abs() < 0.0001);
        }

        #[test]
        fn test_neg() {
            let r = Rational::new(1, 2);
            let neg = -r;
            assert_eq!(neg.num(), -1);
            assert_eq!(neg.den(), 2);
        }

        #[test]
        fn test_ord() {
            let a = Rational::new(1, 2);
            let b = Rational::new(1, 3);
            let c = Rational::new(2, 4);

            assert!(a > b);
            assert!(b < a);
            assert_eq!(a, c);
            assert!(a >= c);
            assert!(a <= c);
        }

        #[test]
        fn test_from_i32() {
            let r: Rational = 5.into();
            assert_eq!(r.num(), 5);
            assert_eq!(r.den(), 1);
        }

        #[test]
        fn test_from_tuple() {
            let r: Rational = (3, 4).into();
            assert_eq!(r.num(), 3);
            assert_eq!(r.den(), 4);
        }

        #[test]
        fn test_display() {
            assert_eq!(format!("{}", Rational::new(1, 2)), "1/2");
            assert_eq!(format!("{}", Rational::new(-3, 4)), "-3/4");
        }

        #[test]
        fn test_default() {
            assert_eq!(Rational::default(), Rational::one());
        }

        #[test]
        fn test_common_frame_rates() {
            // 23.976 fps (film)
            let fps = Rational::new(24000, 1001);
            assert!((fps.as_f64() - 23.976).abs() < 0.001);

            // 29.97 fps (NTSC)
            let fps = Rational::new(30000, 1001);
            assert!((fps.as_f64() - 29.97).abs() < 0.01);

            // 59.94 fps (NTSC interlaced as progressive)
            let fps = Rational::new(60000, 1001);
            assert!((fps.as_f64() - 59.94).abs() < 0.01);
        }
    }

    // ==================== GCD Tests ====================

    #[test]
    fn test_gcd() {
        assert_eq!(gcd(12, 8), 4);
        assert_eq!(gcd(17, 13), 1);
        assert_eq!(gcd(100, 25), 25);
        assert_eq!(gcd(0, 5), 5);
        assert_eq!(gcd(5, 0), 5);
    }
}