oximedia-timecode 0.1.5

LTC and VITC timecode reading and writing for OxiMedia
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
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
//! OxiMedia Timecode - LTC and VITC reading and writing
//!
//! This crate provides SMPTE 12M compliant timecode reading and writing for:
//! - LTC (Linear Timecode) - audio-based timecode
//! - VITC (Vertical Interval Timecode) - video line-based timecode
//!
//! # Features
//! - All standard frame rates (23.976, 24, 25, 29.97, 30, 47.952, 50, 59.94, 60, 120)
//! - Drop frame and non-drop frame support
//! - User bits encoding/decoding
//! - Real-time capable
//! - No unsafe code
#![allow(
    clippy::cast_possible_truncation,
    clippy::cast_precision_loss,
    clippy::cast_sign_loss,
    dead_code,
    clippy::pedantic
)]

pub mod burn_in;
pub mod compare;
pub mod continuity;
pub mod drop_frame;
pub mod duration;
pub mod embedded_tc;
pub mod frame_offset;
pub mod frame_rate;
pub mod jam_sync;
pub mod ltc;
pub mod ltc_encoder;
pub mod ltc_parser;
pub mod ltc_simd;
pub mod midi_timecode;
pub mod reader;
pub mod subframe;
pub mod sync;
pub mod sync_map;
pub mod tc_calculator;
pub mod tc_compare;
pub mod tc_convert;
pub mod tc_drift;
pub mod tc_interpolate;
pub mod tc_list;
pub mod tc_math;
pub mod tc_metadata;
pub mod tc_offset_table;
pub mod tc_range;
pub mod tc_sequence;
pub mod tc_smpte_ranges;
pub mod tc_subtitle_sync;
pub mod tc_validator;
pub mod timecode_calculator;
pub mod timecode_display;
pub mod timecode_event;
pub mod timecode_format;
pub mod timecode_generator;
pub mod timecode_log;
pub mod timecode_overlay;
pub mod timecode_range;
pub mod vitc;

use std::fmt;

/// SMPTE timecode frame rates
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum FrameRate {
    /// 23.976 fps (film transferred to NTSC, non-drop frame)
    Fps23976,
    /// 23.976 fps drop frame (drops 2 frames every 10 minutes)
    Fps23976DF,
    /// 24 fps (film)
    Fps24,
    /// 25 fps (PAL)
    Fps25,
    /// 29.97 fps (NTSC drop frame)
    Fps2997DF,
    /// 29.97 fps (NTSC non-drop frame)
    Fps2997NDF,
    /// 30 fps
    Fps30,
    /// 47.952 fps (cinema HFR, pulled-down from 48fps, non-drop frame)
    Fps47952,
    /// 47.952 fps drop frame (drops 4 frames every 10 minutes)
    Fps47952DF,
    /// 50 fps (PAL progressive)
    Fps50,
    /// 59.94 fps (NTSC progressive, non-drop frame)
    Fps5994,
    /// 59.94 fps drop frame (drops 4 frames every 10 minutes)
    Fps5994DF,
    /// 60 fps
    Fps60,
    /// 120 fps (high frame rate display / VR)
    Fps120,
}

impl FrameRate {
    /// Get the nominal frame rate as a float
    pub fn as_float(&self) -> f64 {
        match self {
            FrameRate::Fps23976 | FrameRate::Fps23976DF => 24000.0 / 1001.0,
            FrameRate::Fps24 => 24.0,
            FrameRate::Fps25 => 25.0,
            FrameRate::Fps2997DF | FrameRate::Fps2997NDF => 30000.0 / 1001.0,
            FrameRate::Fps30 => 30.0,
            FrameRate::Fps47952 | FrameRate::Fps47952DF => 48000.0 / 1001.0,
            FrameRate::Fps50 => 50.0,
            FrameRate::Fps5994 | FrameRate::Fps5994DF => 60000.0 / 1001.0,
            FrameRate::Fps60 => 60.0,
            FrameRate::Fps120 => 120.0,
        }
    }

    /// Get the exact frame rate as a rational (numerator, denominator)
    pub fn as_rational(&self) -> (u32, u32) {
        match self {
            FrameRate::Fps23976 | FrameRate::Fps23976DF => (24000, 1001),
            FrameRate::Fps24 => (24, 1),
            FrameRate::Fps25 => (25, 1),
            FrameRate::Fps2997DF | FrameRate::Fps2997NDF => (30000, 1001),
            FrameRate::Fps30 => (30, 1),
            FrameRate::Fps47952 | FrameRate::Fps47952DF => (48000, 1001),
            FrameRate::Fps50 => (50, 1),
            FrameRate::Fps5994 | FrameRate::Fps5994DF => (60000, 1001),
            FrameRate::Fps60 => (60, 1),
            FrameRate::Fps120 => (120, 1),
        }
    }

    /// Check if this is a drop frame rate
    pub fn is_drop_frame(&self) -> bool {
        matches!(
            self,
            FrameRate::Fps2997DF
                | FrameRate::Fps23976DF
                | FrameRate::Fps5994DF
                | FrameRate::Fps47952DF
        )
    }

    /// The number of frames dropped per discontinuity point (every non-10th minute boundary).
    ///
    /// For 29.97 DF: 2 frames dropped per minute.
    /// For 23.976 DF: 2 frames dropped per minute (scaled from 29.97 × 24/30).
    /// For 47.952 DF: 4 frames dropped per minute (scaled from 29.97 × 48/30).
    /// For 59.94 DF: 4 frames dropped per minute (scaled from 29.97 × 60/30).
    pub fn drop_frames_per_minute(&self) -> u64 {
        match self {
            FrameRate::Fps23976DF => 2,
            FrameRate::Fps2997DF => 2,
            FrameRate::Fps47952DF => 4,
            FrameRate::Fps5994DF => 4,
            _ => 0,
        }
    }

    /// Get the number of frames per second (rounded)
    pub fn frames_per_second(&self) -> u32 {
        match self {
            FrameRate::Fps23976 | FrameRate::Fps23976DF => 24,
            FrameRate::Fps24 => 24,
            FrameRate::Fps25 => 25,
            FrameRate::Fps2997DF | FrameRate::Fps2997NDF => 30,
            FrameRate::Fps30 => 30,
            FrameRate::Fps47952 | FrameRate::Fps47952DF => 48,
            FrameRate::Fps50 => 50,
            FrameRate::Fps5994 | FrameRate::Fps5994DF => 60,
            FrameRate::Fps60 => 60,
            FrameRate::Fps120 => 120,
        }
    }
}

/// Frame rate information for timecode (embedded in Timecode struct)
#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
pub struct FrameRateInfo {
    /// Frames per second (rounded)
    pub fps: u8,
    /// Drop frame flag
    pub drop_frame: bool,
}

impl PartialEq for FrameRateInfo {
    fn eq(&self, other: &Self) -> bool {
        self.fps == other.fps && self.drop_frame == other.drop_frame
    }
}

impl Eq for FrameRateInfo {}

/// Reconstruct a [`FrameRate`] enum from a [`FrameRateInfo`] embedded in a [`Timecode`].
///
/// This is a best-effort reconstruction: it cannot distinguish e.g. `Fps23976` from `Fps24`
/// (both have nominal fps=24) without the drop-frame flag, so it uses the drop-frame flag
/// and nominal fps to select the most common matching variant.
pub fn frame_rate_from_info(info: &FrameRateInfo) -> FrameRate {
    match (info.fps, info.drop_frame) {
        (24, true) => FrameRate::Fps23976DF,
        (24, false) => FrameRate::Fps23976, // Conservative: assume pull-down variant
        (25, _) => FrameRate::Fps25,
        (30, true) => FrameRate::Fps2997DF,
        (30, false) => FrameRate::Fps2997NDF,
        (48, true) => FrameRate::Fps47952DF,
        (48, false) => FrameRate::Fps47952,
        (50, _) => FrameRate::Fps50,
        (60, true) => FrameRate::Fps5994DF,
        (60, false) => FrameRate::Fps5994,
        (120, _) => FrameRate::Fps120,
        _ => FrameRate::Fps25, // Fallback
    }
}

/// SMPTE timecode structure
///
/// The `frame_count_cache` field stores the pre-computed total frame count
/// from midnight, avoiding recomputation on repeated calls to `to_frames()`.
/// It is excluded from equality comparison and serialization so it does not
/// affect timecode identity or wire format.
#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
pub struct Timecode {
    /// Hours (0-23)
    pub hours: u8,
    /// Minutes (0-59)
    pub minutes: u8,
    /// Seconds (0-59)
    pub seconds: u8,
    /// Frames (0 to frame_rate - 1)
    pub frames: u8,
    /// Frame rate
    pub frame_rate: FrameRateInfo,
    /// User bits (32 bits)
    pub user_bits: u32,
    /// Cached total frame count from midnight (computed at construction, excluded from Eq)
    #[serde(skip)]
    frame_count_cache: u64,
}

impl PartialEq for Timecode {
    fn eq(&self, other: &Self) -> bool {
        self.hours == other.hours
            && self.minutes == other.minutes
            && self.seconds == other.seconds
            && self.frames == other.frames
            && self.frame_rate == other.frame_rate
            && self.user_bits == other.user_bits
    }
}

impl Eq for Timecode {}

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

impl Ord for Timecode {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.to_frames().cmp(&other.to_frames())
    }
}

impl Timecode {
    /// Compute total frames from midnight from the component fields.
    /// This is the canonical calculation used by the constructor and cache.
    fn compute_frames_from_fields(
        hours: u8,
        minutes: u8,
        seconds: u8,
        frames: u8,
        fps: u64,
        drop_frame: bool,
    ) -> u64 {
        let mut total = hours as u64 * 3600 * fps;
        total += minutes as u64 * 60 * fps;
        total += seconds as u64 * fps;
        total += frames as u64;

        if drop_frame {
            let drop_per_min = if fps >= 60 { 4u64 } else { 2u64 };
            let total_minutes = hours as u64 * 60 + minutes as u64;
            let dropped_frames = drop_per_min * (total_minutes - total_minutes / 10);
            total -= dropped_frames;
        }

        total
    }

    /// Create a new timecode
    pub fn new(
        hours: u8,
        minutes: u8,
        seconds: u8,
        frames: u8,
        frame_rate: FrameRate,
    ) -> Result<Self, TimecodeError> {
        let fps = frame_rate.frames_per_second() as u8;

        if hours > 23 {
            return Err(TimecodeError::InvalidHours);
        }
        if minutes > 59 {
            return Err(TimecodeError::InvalidMinutes);
        }
        if seconds > 59 {
            return Err(TimecodeError::InvalidSeconds);
        }
        if frames >= fps {
            return Err(TimecodeError::InvalidFrames);
        }

        // Validate drop frame rules
        if frame_rate.is_drop_frame() {
            let drop_count = frame_rate.drop_frames_per_minute() as u8;
            // drop_count frames are dropped at the start of each minute,
            // except minutes 0, 10, 20, 30, 40, 50.
            if seconds == 0 && frames < drop_count && !minutes.is_multiple_of(10) {
                return Err(TimecodeError::InvalidDropFrame);
            }
        }

        let drop_frame = frame_rate.is_drop_frame();
        let frame_count_cache = Self::compute_frames_from_fields(
            hours, minutes, seconds, frames, fps as u64, drop_frame,
        );

        Ok(Timecode {
            hours,
            minutes,
            seconds,
            frames,
            frame_rate: FrameRateInfo { fps, drop_frame },
            user_bits: 0,
            frame_count_cache,
        })
    }

    /// Parse a SMPTE timecode string.
    ///
    /// Accepts both "HH:MM:SS:FF" (non-drop frame, all colons) and
    /// "HH:MM:SS;FF" (drop frame, semicolon before frames).
    ///
    /// The `frame_rate` parameter determines the frame rate; the separator
    /// before the frame field determines whether drop-frame validation applies.
    ///
    /// # Errors
    ///
    /// Returns an error if the string format is invalid or component values
    /// are out of range.
    pub fn from_string(s: &str, frame_rate: FrameRate) -> Result<Self, TimecodeError> {
        let s = s.trim();
        // Minimum length: "00:00:00:00" = 11 chars
        if s.len() < 11 {
            return Err(TimecodeError::InvalidConfiguration);
        }

        // Split on colons and semicolons. Expect exactly 4 parts.
        let parts: Vec<&str> = s.split([':', ';']).collect();
        if parts.len() != 4 {
            return Err(TimecodeError::InvalidConfiguration);
        }

        let hours: u8 = parts[0].parse().map_err(|_| TimecodeError::InvalidHours)?;
        let minutes: u8 = parts[1]
            .parse()
            .map_err(|_| TimecodeError::InvalidMinutes)?;
        let seconds: u8 = parts[2]
            .parse()
            .map_err(|_| TimecodeError::InvalidSeconds)?;
        let frames: u8 = parts[3].parse().map_err(|_| TimecodeError::InvalidFrames)?;

        Self::new(hours, minutes, seconds, frames, frame_rate)
    }

    /// Create a `Timecode` directly from raw fields without constructor validation.
    ///
    /// This is intended for internal use in parsers and codecs where the
    /// component values have already been validated by the caller.
    /// The `frame_count_cache` is computed automatically.
    pub fn from_raw_fields(
        hours: u8,
        minutes: u8,
        seconds: u8,
        frames: u8,
        fps: u8,
        drop_frame: bool,
        user_bits: u32,
    ) -> Self {
        let frame_count_cache = Self::compute_frames_from_fields(
            hours, minutes, seconds, frames, fps as u64, drop_frame,
        );
        Self {
            hours,
            minutes,
            seconds,
            frames,
            frame_rate: FrameRateInfo { fps, drop_frame },
            user_bits,
            frame_count_cache,
        }
    }

    /// Create timecode with user bits
    pub fn with_user_bits(mut self, user_bits: u32) -> Self {
        self.user_bits = user_bits;
        self
    }

    /// Convert to total frames since midnight.
    ///
    /// Returns the cached value computed at construction time — O(1).
    #[inline]
    pub fn to_frames(&self) -> u64 {
        self.frame_count_cache
    }

    /// Convert this timecode to elapsed wall-clock seconds as f64.
    ///
    /// For pull-down rates (23.976, 29.97, 47.952, 59.94) the exact rational
    /// frame rate is used so the result is frame-accurate.
    #[allow(clippy::cast_precision_loss)]
    pub fn to_seconds_f64(&self) -> f64 {
        let rate = frame_rate_from_info(&self.frame_rate);
        let (num, den) = rate.as_rational();
        // Use the exact rational to avoid floating-point drift at pull-down rates.
        self.frame_count_cache as f64 * den as f64 / num as f64
    }

    /// Create from total frames since midnight
    pub fn from_frames(frames: u64, frame_rate: FrameRate) -> Result<Self, TimecodeError> {
        let fps = frame_rate.frames_per_second() as u64;
        let mut remaining = frames;

        // Adjust for drop frame (generalised to support 2-frame and 4-frame drop rates)
        if frame_rate.is_drop_frame() {
            let drop_per_min = frame_rate.drop_frames_per_minute();
            let frames_per_minute = fps * 60 - drop_per_min;
            let frames_per_10_minutes = frames_per_minute * 9 + fps * 60;

            let ten_minute_blocks = remaining / frames_per_10_minutes;
            remaining += ten_minute_blocks * (drop_per_min * 9);

            let remaining_in_block = remaining % frames_per_10_minutes;
            if remaining_in_block >= fps * 60 {
                let extra_minutes = (remaining_in_block - fps * 60) / frames_per_minute;
                remaining += (extra_minutes + 1) * drop_per_min;
            }
        }

        let hours = (remaining / (fps * 3600)) as u8;
        remaining %= fps * 3600;
        let minutes = (remaining / (fps * 60)) as u8;
        remaining %= fps * 60;
        let seconds = (remaining / fps) as u8;
        let frame = (remaining % fps) as u8;

        Self::new(hours, minutes, seconds, frame, frame_rate)
    }

    /// Increment by one frame
    pub fn increment(&mut self) -> Result<(), TimecodeError> {
        self.frames += 1;

        if self.frames >= self.frame_rate.fps {
            self.frames = 0;
            self.seconds += 1;

            if self.seconds >= 60 {
                self.seconds = 0;
                self.minutes += 1;

                // Handle drop frame: skip frame numbers 0..drop_count at non-10th-minute boundaries
                if self.frame_rate.drop_frame && !self.minutes.is_multiple_of(10) {
                    let drop_count = if self.frame_rate.fps >= 60 { 4u8 } else { 2u8 };
                    self.frames = drop_count;
                }

                if self.minutes >= 60 {
                    self.minutes = 0;
                    self.hours += 1;

                    if self.hours >= 24 {
                        self.hours = 0;
                    }
                }
            }
        }

        // Recompute cache after mutation
        self.frame_count_cache = Self::compute_frames_from_fields(
            self.hours,
            self.minutes,
            self.seconds,
            self.frames,
            self.frame_rate.fps as u64,
            self.frame_rate.drop_frame,
        );

        Ok(())
    }

    /// Decrement by one frame
    pub fn decrement(&mut self) -> Result<(), TimecodeError> {
        if self.frames > 0 {
            self.frames -= 1;

            // Check if we're in a drop frame position
            let drop_count = if self.frame_rate.fps >= 60 { 4u8 } else { 2u8 };
            if self.frame_rate.drop_frame
                && self.seconds == 0
                && self.frames < drop_count
                && !self.minutes.is_multiple_of(10)
            {
                self.frames = self.frame_rate.fps - 1;
                if self.seconds > 0 {
                    self.seconds -= 1;
                } else {
                    self.seconds = 59;
                    if self.minutes > 0 {
                        self.minutes -= 1;
                    } else {
                        self.minutes = 59;
                        if self.hours > 0 {
                            self.hours -= 1;
                        } else {
                            self.hours = 23;
                        }
                    }
                }
            }
        } else if self.seconds > 0 {
            self.seconds -= 1;
            self.frames = self.frame_rate.fps - 1;
        } else {
            self.seconds = 59;
            self.frames = self.frame_rate.fps - 1;

            if self.minutes > 0 {
                self.minutes -= 1;
            } else {
                self.minutes = 59;
                if self.hours > 0 {
                    self.hours -= 1;
                } else {
                    self.hours = 23;
                }
            }
        }

        // Recompute cache after mutation
        self.frame_count_cache = Self::compute_frames_from_fields(
            self.hours,
            self.minutes,
            self.seconds,
            self.frames,
            self.frame_rate.fps as u64,
            self.frame_rate.drop_frame,
        );

        Ok(())
    }
}

// ---------------------------------------------------------------------------
// Arithmetic operators
// ---------------------------------------------------------------------------

impl std::ops::Add for Timecode {
    type Output = Result<Timecode, TimecodeError>;

    /// Add two timecodes by summing their total frame counts.
    ///
    /// The result uses the frame rate of `self`. The frame counts wrap at a
    /// 24-hour boundary.
    fn add(self, rhs: Timecode) -> Self::Output {
        let rate = frame_rate_from_info(&self.frame_rate);
        let fps = self.frame_rate.fps as u64;
        let frames_per_day = fps * 86_400;

        let sum = if frames_per_day > 0 {
            (self.frame_count_cache + rhs.frame_count_cache) % frames_per_day
        } else {
            self.frame_count_cache + rhs.frame_count_cache
        };

        Timecode::from_frames(sum, rate)
    }
}

impl std::ops::Sub for Timecode {
    type Output = Result<Timecode, TimecodeError>;

    /// Subtract `rhs` from `self` by frame count.
    ///
    /// The result uses the frame rate of `self`. Underflow wraps at a
    /// 24-hour boundary.
    fn sub(self, rhs: Timecode) -> Self::Output {
        let rate = frame_rate_from_info(&self.frame_rate);
        let fps = self.frame_rate.fps as u64;
        let frames_per_day = fps * 86_400;

        let result = if frames_per_day > 0 {
            if self.frame_count_cache >= rhs.frame_count_cache {
                self.frame_count_cache - rhs.frame_count_cache
            } else {
                // Wrap: borrow one 24-hour day
                frames_per_day - (rhs.frame_count_cache - self.frame_count_cache) % frames_per_day
            }
        } else {
            self.frame_count_cache.saturating_sub(rhs.frame_count_cache)
        };

        Timecode::from_frames(result, rate)
    }
}

impl std::ops::Add<u32> for Timecode {
    type Output = Result<Timecode, TimecodeError>;

    /// Add `rhs` frames to `self`, wrapping at a 24-hour boundary.
    ///
    /// The result uses the frame rate of `self`.
    fn add(self, rhs: u32) -> Self::Output {
        let rate = frame_rate_from_info(&self.frame_rate);
        let fps = self.frame_rate.fps as u64;
        let frames_per_day = fps * 86_400;

        let sum = if frames_per_day > 0 {
            (self.frame_count_cache + rhs as u64) % frames_per_day
        } else {
            self.frame_count_cache + rhs as u64
        };

        Timecode::from_frames(sum, rate)
    }
}

// ---------------------------------------------------------------------------
// Display
// ---------------------------------------------------------------------------

impl fmt::Display for Timecode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let separator = if self.frame_rate.drop_frame { ';' } else { ':' };
        write!(
            f,
            "{:02}:{:02}:{:02}{}{:02}",
            self.hours, self.minutes, self.seconds, separator, self.frames
        )
    }
}

// ---------------------------------------------------------------------------
// Traits
// ---------------------------------------------------------------------------

/// Timecode reader trait
pub trait TimecodeReader {
    /// Read the next timecode from the source
    fn read_timecode(&mut self) -> Result<Option<Timecode>, TimecodeError>;

    /// Get the current frame rate
    fn frame_rate(&self) -> FrameRate;

    /// Check if the reader is synchronized
    fn is_synchronized(&self) -> bool;
}

/// Timecode writer trait
pub trait TimecodeWriter {
    /// Write a timecode to the output
    fn write_timecode(&mut self, timecode: &Timecode) -> Result<(), TimecodeError>;

    /// Get the current frame rate
    fn frame_rate(&self) -> FrameRate;

    /// Flush any buffered data
    fn flush(&mut self) -> Result<(), TimecodeError>;
}

// ---------------------------------------------------------------------------
// Error type
// ---------------------------------------------------------------------------

/// Timecode errors
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TimecodeError {
    /// Invalid hours value
    InvalidHours,
    /// Invalid minutes value
    InvalidMinutes,
    /// Invalid seconds value
    InvalidSeconds,
    /// Invalid frames value
    InvalidFrames,
    /// Invalid drop frame timecode
    InvalidDropFrame,
    /// Sync word not found
    SyncNotFound,
    /// CRC error
    CrcError,
    /// Buffer too small
    BufferTooSmall,
    /// Invalid configuration
    InvalidConfiguration,
    /// IO error
    IoError(String),
    /// Not synchronized
    NotSynchronized,
}

impl fmt::Display for TimecodeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            TimecodeError::InvalidHours => write!(f, "Invalid hours value"),
            TimecodeError::InvalidMinutes => write!(f, "Invalid minutes value"),
            TimecodeError::InvalidSeconds => write!(f, "Invalid seconds value"),
            TimecodeError::InvalidFrames => write!(f, "Invalid frames value"),
            TimecodeError::InvalidDropFrame => write!(f, "Invalid drop frame timecode"),
            TimecodeError::SyncNotFound => write!(f, "Sync word not found"),
            TimecodeError::CrcError => write!(f, "CRC error"),
            TimecodeError::BufferTooSmall => write!(f, "Buffer too small"),
            TimecodeError::InvalidConfiguration => write!(f, "Invalid configuration"),
            TimecodeError::IoError(e) => write!(f, "IO error: {}", e),
            TimecodeError::NotSynchronized => write!(f, "Not synchronized"),
        }
    }
}

impl std::error::Error for TimecodeError {}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    #[test]
    fn test_timecode_creation() {
        let tc = Timecode::new(1, 2, 3, 4, FrameRate::Fps25).expect("valid timecode");
        assert_eq!(tc.hours, 1);
        assert_eq!(tc.minutes, 2);
        assert_eq!(tc.seconds, 3);
        assert_eq!(tc.frames, 4);
    }

    #[test]
    fn test_timecode_display() {
        let tc = Timecode::new(1, 2, 3, 4, FrameRate::Fps25).expect("valid timecode");
        assert_eq!(tc.to_string(), "01:02:03:04");

        let tc_df = Timecode::new(1, 2, 3, 4, FrameRate::Fps2997DF).expect("valid timecode");
        assert_eq!(tc_df.to_string(), "01:02:03;04");
    }

    #[test]
    fn test_timecode_increment() {
        let mut tc = Timecode::new(0, 0, 0, 24, FrameRate::Fps25).expect("valid timecode");
        tc.increment().expect("increment should succeed");
        assert_eq!(tc.frames, 0);
        assert_eq!(tc.seconds, 1);
    }

    #[test]
    fn test_frame_rate() {
        assert_eq!(FrameRate::Fps25.as_float(), 25.0);
        assert!((FrameRate::Fps2997DF.as_float() - 29.97002997).abs() < 1e-6);
        assert!(FrameRate::Fps2997DF.is_drop_frame());
        assert!(!FrameRate::Fps2997NDF.is_drop_frame());
    }

    #[test]
    fn test_framerate_47952_and_120() {
        assert_eq!(FrameRate::Fps47952.frames_per_second(), 48);
        assert_eq!(FrameRate::Fps47952DF.frames_per_second(), 48);
        assert_eq!(FrameRate::Fps120.frames_per_second(), 120);
        assert!(!FrameRate::Fps47952.is_drop_frame());
        assert!(FrameRate::Fps47952DF.is_drop_frame());
        assert!(!FrameRate::Fps120.is_drop_frame());
        assert_eq!(FrameRate::Fps47952.as_rational(), (48000, 1001));
        assert_eq!(FrameRate::Fps120.as_rational(), (120, 1));
    }

    #[test]
    fn test_from_string_ndf() {
        let tc = Timecode::from_string("01:02:03:04", FrameRate::Fps25).expect("should parse");
        assert_eq!(tc.hours, 1);
        assert_eq!(tc.minutes, 2);
        assert_eq!(tc.seconds, 3);
        assert_eq!(tc.frames, 4);
    }

    #[test]
    fn test_from_string_df() {
        // Drop frame: semicolon before frames
        let tc = Timecode::from_string("01:02:03;04", FrameRate::Fps2997DF).expect("should parse");
        assert_eq!(tc.frames, 4);
        assert!(tc.frame_rate.drop_frame);
    }

    #[test]
    fn test_from_string_invalid_too_short() {
        assert!(Timecode::from_string("1:2:3:4", FrameRate::Fps25).is_err());
    }

    #[test]
    fn test_from_string_invalid_parts() {
        assert!(Timecode::from_string("01:02:03", FrameRate::Fps25).is_err());
    }

    #[test]
    fn test_to_seconds_f64_one_hour_25fps() {
        let tc = Timecode::new(1, 0, 0, 0, FrameRate::Fps25).expect("valid");
        let secs = tc.to_seconds_f64();
        assert!((secs - 3600.0).abs() < 1e-6);
    }

    #[test]
    fn test_to_seconds_f64_pull_down() {
        // 1 frame at 29.97 NDF = 1001/30000 seconds
        let tc = Timecode::new(0, 0, 0, 1, FrameRate::Fps2997NDF).expect("valid");
        let expected = 1001.0 / 30000.0;
        assert!((tc.to_seconds_f64() - expected).abs() < 1e-12);
    }

    #[test]
    fn test_ord_timecodes() {
        let tc1 = Timecode::new(0, 0, 0, 0, FrameRate::Fps25).expect("valid");
        let tc2 = Timecode::new(0, 0, 0, 1, FrameRate::Fps25).expect("valid");
        let tc3 = Timecode::new(1, 0, 0, 0, FrameRate::Fps25).expect("valid");
        assert!(tc1 < tc2);
        assert!(tc2 < tc3);
        assert!(tc1 < tc3);
        assert_eq!(tc1, tc1);
    }

    #[test]
    fn test_add_timecodes() {
        let tc1 = Timecode::new(0, 0, 1, 0, FrameRate::Fps25).expect("valid"); // 1s
        let tc2 = Timecode::new(0, 0, 2, 0, FrameRate::Fps25).expect("valid"); // 2s
        let result = (tc1 + tc2).expect("add should succeed");
        assert_eq!(result.seconds, 3);
        assert_eq!(result.frames, 0);
    }

    #[test]
    fn test_sub_timecodes() {
        let tc1 = Timecode::new(0, 0, 3, 0, FrameRate::Fps25).expect("valid"); // 3s
        let tc2 = Timecode::new(0, 0, 1, 0, FrameRate::Fps25).expect("valid"); // 1s
        let result = (tc1 - tc2).expect("sub should succeed");
        assert_eq!(result.seconds, 2);
        assert_eq!(result.frames, 0);
    }

    #[test]
    fn test_add_u32_frames() {
        // 0:00:00:00 + 25 frames = 0:00:01:00 at 25fps
        let tc = Timecode::new(0, 0, 0, 0, FrameRate::Fps25).expect("valid");
        let result = (tc + 25_u32).expect("add u32 should succeed");
        assert_eq!(result.seconds, 1);
        assert_eq!(result.frames, 0);

        // 23:59:59:24 + 1 frame wraps to 0:00:00:00
        let tc_near_end = Timecode::new(23, 59, 59, 24, FrameRate::Fps25).expect("valid");
        let wrapped = (tc_near_end + 1_u32).expect("wrap should succeed");
        assert_eq!(wrapped.hours, 0);
        assert_eq!(wrapped.minutes, 0);
        assert_eq!(wrapped.seconds, 0);
        assert_eq!(wrapped.frames, 0);
    }

    #[test]
    fn test_frame_count_cache_matches_recomputed() {
        let tc = Timecode::new(1, 23, 45, 12, FrameRate::Fps25).expect("valid");
        let expected: u64 = 1 * 3600 * 25 + 23 * 60 * 25 + 45 * 25 + 12;
        assert_eq!(tc.to_frames(), expected);
    }

    #[test]
    fn test_frame_count_cache_after_increment() {
        let mut tc = Timecode::new(0, 0, 0, 24, FrameRate::Fps25).expect("valid");
        let before = tc.to_frames();
        tc.increment().expect("ok");
        assert_eq!(tc.to_frames(), before + 1);
    }

    #[test]
    fn test_frame_rate_from_info() {
        let info = FrameRateInfo {
            fps: 25,
            drop_frame: false,
        };
        assert_eq!(frame_rate_from_info(&info), FrameRate::Fps25);

        let info_df = FrameRateInfo {
            fps: 30,
            drop_frame: true,
        };
        assert_eq!(frame_rate_from_info(&info_df), FrameRate::Fps2997DF);

        let info_120 = FrameRateInfo {
            fps: 120,
            drop_frame: false,
        };
        assert_eq!(frame_rate_from_info(&info_120), FrameRate::Fps120);
    }
}