oximedia-timecode 0.1.3

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
#![allow(dead_code)]
//! Timecode format conversion utilities.
//!
//! Converts timecodes between different frame rates, between wall-clock time
//! and timecode, and between SMPTE string representations and frame numbers.

use crate::{FrameRate, Timecode, TimecodeError};

/// Strategy for converting timecodes between different frame rates.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConvertStrategy {
    /// Preserve the wall-clock time as closely as possible.
    PreserveTime,
    /// Preserve the frame number (snap to nearest frame in target rate).
    PreserveFrame,
    /// Preserve the HH:MM:SS:FF display string (may change actual time).
    PreserveDisplay,
}

/// Result of a timecode conversion.
#[derive(Debug, Clone)]
pub struct ConvertResult {
    /// The converted timecode
    pub timecode: Timecode,
    /// The rounding error in seconds (positive means output is later)
    pub rounding_error_secs: f64,
    /// Whether the conversion was exact (no rounding)
    pub exact: bool,
}

/// Converts a timecode from one frame rate to another.
///
/// # Errors
///
/// Returns an error if the target timecode is invalid (e.g., exceeds 24h).
#[allow(clippy::cast_precision_loss)]
pub fn convert_frame_rate(
    tc: &Timecode,
    target_rate: FrameRate,
    strategy: ConvertStrategy,
) -> Result<ConvertResult, TimecodeError> {
    match strategy {
        ConvertStrategy::PreserveTime => convert_preserve_time(tc, target_rate),
        ConvertStrategy::PreserveFrame => convert_preserve_frame(tc, target_rate),
        ConvertStrategy::PreserveDisplay => convert_preserve_display(tc, target_rate),
    }
}

/// Converts preserving wall-clock time.
#[allow(clippy::cast_precision_loss)]
fn convert_preserve_time(
    tc: &Timecode,
    target_rate: FrameRate,
) -> Result<ConvertResult, TimecodeError> {
    let source_fps = if tc.frame_rate.drop_frame {
        29.97
    } else {
        tc.frame_rate.fps as f64
    };
    let src_frames = tc.to_frames();
    let time_secs = src_frames as f64 / source_fps;

    let target_fps = target_rate.as_float();
    let target_frames = (time_secs * target_fps).round() as u64;

    let result_tc = Timecode::from_frames(target_frames, target_rate)?;
    let result_time = target_frames as f64 / target_fps;
    let error = result_time - time_secs;

    Ok(ConvertResult {
        timecode: result_tc,
        rounding_error_secs: error,
        exact: error.abs() < 1e-9,
    })
}

/// Converts preserving the frame number (modulo target fps).
#[allow(clippy::cast_precision_loss)]
fn convert_preserve_frame(
    tc: &Timecode,
    target_rate: FrameRate,
) -> Result<ConvertResult, TimecodeError> {
    let src_frames = tc.to_frames();
    let result_tc = Timecode::from_frames(src_frames, target_rate)?;
    let source_fps = if tc.frame_rate.drop_frame {
        29.97
    } else {
        tc.frame_rate.fps as f64
    };
    let target_fps = target_rate.as_float();
    let error = src_frames as f64 * (1.0 / target_fps - 1.0 / source_fps);

    Ok(ConvertResult {
        timecode: result_tc,
        rounding_error_secs: error,
        exact: (source_fps - target_fps).abs() < 1e-9,
    })
}

/// Converts preserving the HH:MM:SS:FF display.
#[allow(clippy::cast_precision_loss)]
fn convert_preserve_display(
    tc: &Timecode,
    target_rate: FrameRate,
) -> Result<ConvertResult, TimecodeError> {
    let target_fps = target_rate.frames_per_second() as u8;
    let frames = if tc.frames >= target_fps {
        target_fps - 1
    } else {
        tc.frames
    };
    let result_tc = Timecode::new(tc.hours, tc.minutes, tc.seconds, frames, target_rate)?;
    let source_fps = if tc.frame_rate.drop_frame {
        29.97
    } else {
        tc.frame_rate.fps as f64
    };
    let tfps = target_rate.as_float();
    let src_time = tc.to_frames() as f64 / source_fps;
    let dst_time = result_tc.to_frames() as f64 / tfps;

    Ok(ConvertResult {
        timecode: result_tc,
        rounding_error_secs: dst_time - src_time,
        exact: false,
    })
}

/// Converts a wall-clock duration in seconds to a timecode.
///
/// # Errors
///
/// Returns an error if the duration exceeds 24 hours.
#[allow(clippy::cast_precision_loss)]
pub fn seconds_to_timecode(secs: f64, rate: FrameRate) -> Result<Timecode, TimecodeError> {
    if secs < 0.0 {
        return Err(TimecodeError::InvalidConfiguration);
    }
    let fps = rate.as_float();
    let total_frames = (secs * fps).round() as u64;
    Timecode::from_frames(total_frames, rate)
}

/// Converts a timecode to wall-clock seconds.
#[allow(clippy::cast_precision_loss)]
pub fn timecode_to_seconds(tc: &Timecode) -> f64 {
    let fps = if tc.frame_rate.drop_frame {
        29.97
    } else {
        tc.frame_rate.fps as f64
    };
    tc.to_frames() as f64 / fps
}

/// Parses a SMPTE timecode string like "01:02:03:04" or "01:02:03;04".
///
/// The separator between seconds and frames determines drop-frame vs non-drop:
/// - `:` for non-drop frame
/// - `;` for drop frame
///
/// # Errors
///
/// Returns an error if the string format is invalid.
pub fn parse_smpte_string(s: &str, rate: FrameRate) -> Result<Timecode, TimecodeError> {
    let s = s.trim();
    if s.len() < 11 {
        return Err(TimecodeError::InvalidConfiguration);
    }
    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)?;

    Timecode::new(hours, minutes, seconds, frames, rate)
}

/// Formats a frame count as an SMPTE timecode string.
///
/// # Errors
///
/// Returns an error if the frame count produces an invalid timecode.
pub fn frames_to_smpte_string(frames: u64, rate: FrameRate) -> Result<String, TimecodeError> {
    let tc = Timecode::from_frames(frames, rate)?;
    Ok(tc.to_string())
}

/// Converts a timecode to a total millisecond value.
#[allow(clippy::cast_precision_loss)]
pub fn timecode_to_millis(tc: &Timecode) -> u64 {
    let secs = timecode_to_seconds(tc);
    (secs * 1000.0).round() as u64
}

/// Converts milliseconds to a timecode.
///
/// # Errors
///
/// Returns an error if the milliseconds value exceeds 24 hours.
pub fn millis_to_timecode(ms: u64, rate: FrameRate) -> Result<Timecode, TimecodeError> {
    #[allow(clippy::cast_precision_loss)]
    let secs = ms as f64 / 1000.0;
    seconds_to_timecode(secs, rate)
}

/// Computes the number of real-time samples (at a given audio sample rate)
/// that correspond to a timecode offset.
#[allow(clippy::cast_precision_loss)]
pub fn timecode_to_audio_samples(tc: &Timecode, sample_rate: u32) -> u64 {
    let secs = timecode_to_seconds(tc);
    (secs * sample_rate as f64).round() as u64
}

// ---------------------------------------------------------------------------
// NDF ↔ DF conversion utilities
// ---------------------------------------------------------------------------

/// Convert a non-drop-frame (NDF) timecode to its drop-frame (DF) equivalent.
///
/// The conversion preserves the wall-clock time as closely as possible:
/// the NDF frame count (at the integer fps) is treated as an absolute frame
/// index, and the equivalent DF timecode at the same nominal fps is returned.
///
/// Currently supports 29.97 NDF → 29.97 DF and 59.94 NDF → 59.94 DF.
///
/// # Errors
///
/// Returns an error if the NDF timecode is not at a rate that has a
/// corresponding DF variant, or if the resulting DF position would be invalid.
pub fn ndf_to_df(tc: &Timecode) -> Result<Timecode, TimecodeError> {
    if tc.frame_rate.drop_frame {
        return Err(TimecodeError::InvalidConfiguration); // Already drop frame
    }

    let df_rate = match tc.frame_rate.fps {
        30 => FrameRate::Fps2997DF,
        60 => FrameRate::Fps5994DF,
        24 => FrameRate::Fps23976DF,
        48 => FrameRate::Fps47952DF,
        _ => return Err(TimecodeError::InvalidConfiguration),
    };

    // The NDF frame count (counted as if purely integer fps) is the canonical
    // frame index.  We reinterpret it as a DF frame index — the DF timecode
    // display will differ slightly from the NDF display, which is the intended
    // behaviour (DF displays real elapsed time, NDF does not).
    Timecode::from_frames(tc.to_frames(), df_rate)
}

/// Convert a drop-frame (DF) timecode to its non-drop-frame (NDF) equivalent.
///
/// The total DF frame count is preserved; the resulting NDF timecode at the
/// same nominal fps will generally display a slightly different
/// HH:MM:SS:FF string because NDF ignores the frame-number skips.
///
/// # Errors
///
/// Returns an error if the timecode is already NDF, or if the fps has no
/// NDF counterpart.
pub fn df_to_ndf(tc: &Timecode) -> Result<Timecode, TimecodeError> {
    if !tc.frame_rate.drop_frame {
        return Err(TimecodeError::InvalidConfiguration); // Already non-drop frame
    }

    let ndf_rate = match tc.frame_rate.fps {
        30 => FrameRate::Fps2997NDF,
        60 => FrameRate::Fps5994,
        24 => FrameRate::Fps23976,
        48 => FrameRate::Fps47952,
        _ => return Err(TimecodeError::InvalidConfiguration),
    };

    Timecode::from_frames(tc.to_frames(), ndf_rate)
}

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

    #[test]
    fn test_seconds_to_timecode_25fps() {
        let tc = seconds_to_timecode(3661.0, FrameRate::Fps25)
            .expect("seconds to timecode should succeed");
        assert_eq!(tc.hours, 1);
        assert_eq!(tc.minutes, 1);
        assert_eq!(tc.seconds, 1);
        assert_eq!(tc.frames, 0);
    }

    #[test]
    fn test_timecode_to_seconds() {
        let tc = Timecode::new(1, 0, 0, 0, FrameRate::Fps25).expect("valid timecode");
        let secs = timecode_to_seconds(&tc);
        assert!((secs - 3600.0).abs() < 0.01);
    }

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

    #[test]
    fn test_parse_smpte_invalid() {
        assert!(parse_smpte_string("bad", FrameRate::Fps25).is_err());
    }

    #[test]
    fn test_frames_to_smpte_string() {
        let s =
            frames_to_smpte_string(25, FrameRate::Fps25).expect("frames to SMPTE should succeed");
        assert_eq!(s, "00:00:01:00");
    }

    #[test]
    fn test_millis_roundtrip() {
        let tc = Timecode::new(0, 1, 30, 0, FrameRate::Fps25).expect("valid timecode");
        let ms = timecode_to_millis(&tc);
        let tc2 =
            millis_to_timecode(ms, FrameRate::Fps25).expect("millis to timecode should succeed");
        assert_eq!(tc.hours, tc2.hours);
        assert_eq!(tc.minutes, tc2.minutes);
        assert_eq!(tc.seconds, tc2.seconds);
    }

    #[test]
    fn test_convert_preserve_time_same_rate() {
        let tc = Timecode::new(1, 0, 0, 0, FrameRate::Fps25).expect("valid timecode");
        let result = convert_frame_rate(&tc, FrameRate::Fps25, ConvertStrategy::PreserveTime)
            .expect("conversion should succeed");
        assert!(result.rounding_error_secs.abs() < 0.001);
    }

    #[test]
    fn test_convert_preserve_time_25_to_30() {
        let tc = Timecode::new(0, 0, 1, 0, FrameRate::Fps25).expect("valid timecode");
        let result = convert_frame_rate(&tc, FrameRate::Fps30, ConvertStrategy::PreserveTime)
            .expect("conversion should succeed");
        assert_eq!(result.timecode.seconds, 1);
        assert_eq!(result.timecode.frames, 0);
    }

    #[test]
    fn test_convert_preserve_display() {
        let tc = Timecode::new(1, 2, 3, 10, FrameRate::Fps30).expect("valid timecode");
        let result = convert_frame_rate(&tc, FrameRate::Fps25, ConvertStrategy::PreserveDisplay)
            .expect("conversion should succeed");
        assert_eq!(result.timecode.hours, 1);
        assert_eq!(result.timecode.minutes, 2);
        assert_eq!(result.timecode.seconds, 3);
        assert_eq!(result.timecode.frames, 10);
    }

    #[test]
    fn test_convert_preserve_frame() {
        let tc = Timecode::new(0, 0, 0, 10, FrameRate::Fps25).expect("valid timecode");
        let result = convert_frame_rate(&tc, FrameRate::Fps30, ConvertStrategy::PreserveFrame)
            .expect("conversion should succeed");
        assert_eq!(result.timecode.frames, 10);
    }

    #[test]
    fn test_audio_samples() {
        let tc = Timecode::new(0, 0, 1, 0, FrameRate::Fps25).expect("valid timecode");
        let samples = timecode_to_audio_samples(&tc, 48000);
        assert_eq!(samples, 48000);
    }

    #[test]
    fn test_negative_seconds_error() {
        assert!(seconds_to_timecode(-1.0, FrameRate::Fps25).is_err());
    }

    #[test]
    fn test_ndf_to_df_29_97() {
        // A 29.97 NDF timecode → 29.97 DF: frame count is preserved
        let ndf = Timecode::new(0, 1, 0, 0, FrameRate::Fps2997NDF).expect("valid NDF");
        let df = ndf_to_df(&ndf).expect("ndf_to_df should succeed");
        assert!(df.frame_rate.drop_frame);
        assert_eq!(df.frame_rate.fps, 30);
        // Frame counts must match
        assert_eq!(ndf.to_frames(), df.to_frames());
    }

    #[test]
    fn test_df_to_ndf_29_97() {
        let df = Timecode::new(0, 1, 0, 2, FrameRate::Fps2997DF).expect("valid DF");
        let ndf = df_to_ndf(&df).expect("df_to_ndf should succeed");
        assert!(!ndf.frame_rate.drop_frame);
        assert_eq!(ndf.frame_rate.fps, 30);
        assert_eq!(df.to_frames(), ndf.to_frames());
    }

    #[test]
    fn test_ndf_to_df_already_df_is_error() {
        let df = Timecode::new(0, 1, 0, 2, FrameRate::Fps2997DF).expect("valid DF");
        assert!(ndf_to_df(&df).is_err());
    }

    #[test]
    fn test_df_to_ndf_already_ndf_is_error() {
        let ndf = Timecode::new(0, 1, 0, 0, FrameRate::Fps2997NDF).expect("valid NDF");
        assert!(df_to_ndf(&ndf).is_err());
    }

    #[test]
    fn test_ndf_to_df_unsupported_rate_is_error() {
        let tc = Timecode::new(0, 0, 1, 0, FrameRate::Fps25).expect("valid");
        assert!(ndf_to_df(&tc).is_err());
    }

    #[test]
    fn test_df_ndf_roundtrip_preserves_frame_count() {
        // Roundtrip: NDF → DF → NDF must preserve the frame count
        let ndf = Timecode::new(1, 23, 45, 12, FrameRate::Fps2997NDF).expect("valid NDF");
        let df = ndf_to_df(&ndf).expect("ndf→df");
        let back = df_to_ndf(&df).expect("df→ndf");
        assert_eq!(ndf.to_frames(), back.to_frames());
    }
}