ctb_formats_pan/time/
timecode.rs

1/* SPDX-License-Identifier: MIT */
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7Permission is hereby granted, free of charge, to any person obtaining a copy of
8this software and associated documentation files (the “Software”), to deal in
9the Software without restriction, including without limitation the rights to
10use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
11the Software, and to permit persons to whom the Software is furnished to do so,
12subject to the following conditions:
13
14The above copyright notice and this permission notice shall be included in all
15copies or substantial portions of the Software.
16
17THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23SOFTWARE.
24*/
25
26//! Timecode conversion helpers (non-drop-frame).
27
28#![allow(
29    clippy::module_name_repetitions,
30    reason = "idiomatic module structure names"
31)]
32
33#[expect(unused_imports, reason = "imported module dependencies")]
34use crate::utilities::*;
35
36/// Converts `HH:MM:SS:FF` timecode to total frames.
37pub fn tcframes(timecode: &str, framerate: i64) -> Result<i64> {
38    let fps = validate_fps(framerate)?;
39    let (h, m, s, f) = parse_timecode(timecode, fps)?;
40
41    let total_seconds = h
42        .checked_mul(3600)
43        .context("hour overflow")?
44        .checked_add(m.checked_mul(60).context("minute overflow")?)
45        .context("time overflow")?
46        .checked_add(s)
47        .context("time overflow")?;
48
49    total_seconds
50        .checked_mul(fps)
51        .context("frame overflow")?
52        .checked_add(f)
53        .context("frame overflow")
54}
55
56/// Formats a frame count as `HH:MM:SS:FF`.
57pub fn timecode(frames: i64, framerate: i64) -> Result<String> {
58    let fps = validate_fps(framerate)?;
59    if frames < 0 {
60        bail!("frames must be non-negative, got {frames}");
61    }
62
63    let fps_u = u128::try_from(fps).context("fps")?;
64    let total = u128::try_from(frames).context("frames")?;
65
66    let total_seconds =
67        total.checked_div(fps_u).context("division by fps failed")?;
68    let f = i64::try_from(
69        total
70            .checked_rem(fps_u)
71            .context("remainder by fps failed")?,
72    )
73    .context("frame number did not fit into i64")?;
74
75    let s = i64::try_from(total_seconds % 60)
76        .context("seconds did not fit into i64")?;
77    let total_minutes = total_seconds / 60;
78
79    let m = i64::try_from(total_minutes % 60)
80        .context("minutes did not fit into i64")?;
81    let h = i64::try_from(total_minutes / 60)
82        .context("hours did not fit into i64")?;
83
84    Ok(format!("{h:02}:{m:02}:{s:02}:{f:02}"))
85}
86
87/// Adds `offset` frames to a timecode.
88pub fn tcadd(textcode: &str, offset: i64, framerate: i64) -> Result<String> {
89    let base = tcframes(textcode, framerate)?;
90    let out = base.checked_add(offset).context("frame overflow")?;
91    if out < 0 {
92        bail!("resulting timecode would be negative ({out})");
93    }
94    timecode(out, framerate)
95}
96
97/// Returns the next-frame timecode for `textcode`.
98pub fn outcode(textcode: &str, framerate: i64) -> Result<String> {
99    tcadd(textcode, 1, framerate)
100}
101
102/// Returns the frame distance between two timecodes.
103///
104/// When `edl` is 0, the result is inclusive (same code => 1).
105pub fn tcdiff(
106    incode: &str,
107    outcode: &str,
108    framerate: i64,
109    edl: i64,
110) -> Result<i64> {
111    let a = tcframes(incode, framerate)?;
112    let b = tcframes(outcode, framerate)?;
113    let diff = b.checked_sub(a).context("frame overflow")?;
114
115    if edl != 0 {
116        return Ok(diff);
117    }
118
119    // Inclusive counts: same => 1 frame.
120    if diff >= 0 {
121        diff.checked_add(1).context("frame overflow")
122    } else {
123        diff.checked_sub(1).context("frame overflow")
124    }
125}
126
127/// Converts a 24fps timecode to 30fps using scaling.
128pub fn tc24to30(timecode_24: &str) -> Result<String> {
129    let f24 = tcframes(timecode_24, 24)?;
130    let f30 = scale_frames(f24, 24, 30)?;
131    timecode(f30, 30)
132}
133
134/// Converts a 30fps timecode to 24fps using scaling.
135pub fn tc30to24(timecode_30: &str) -> Result<String> {
136    let f30 = tcframes(timecode_30, 30)?;
137    let f24 = scale_frames(f30, 30, 24)?;
138    timecode(f24, 24)
139}
140
141fn validate_fps(fps: i64) -> Result<i64> {
142    if fps == 24 || fps == 25 || fps == 30 {
143        return Ok(fps);
144    }
145    bail!("unsupported framerate: {fps} (expected 24, 25, or 30)");
146}
147
148fn parse_timecode(s: &str, fps: i64) -> Result<(i64, i64, i64, i64)> {
149    let raw = s.trim();
150    if raw.is_empty() {
151        bail!("empty timecode");
152    }
153    if raw.contains(';') {
154        bail!("drop-frame timecode is not supported: {raw}");
155    }
156
157    let parts: Vec<&str> = raw.split(':').collect();
158    if parts.len() != 4 {
159        bail!("expected HH:MM:SS:FF, got {raw}");
160    }
161
162    let h = parts
163        .first()
164        .context("Missing hours part")?
165        .trim()
166        .parse::<i64>()
167        .context("hours")?;
168    let m = parts
169        .get(1)
170        .context("Missing minutes part")?
171        .trim()
172        .parse::<i64>()
173        .context("minutes")?;
174    let s = parts
175        .get(2)
176        .context("Missing seconds part")?
177        .trim()
178        .parse::<i64>()
179        .context("seconds")?;
180    let f = parts
181        .get(3)
182        .context("Missing frames part")?
183        .trim()
184        .parse::<i64>()
185        .context("frames")?;
186
187    if h < 0 {
188        bail!("hours must be non-negative, got {h}");
189    }
190    if !(0..=59).contains(&m) {
191        bail!("minutes out of range: {m}");
192    }
193    if !(0..=59).contains(&s) {
194        bail!("seconds out of range: {s}");
195    }
196    if f < 0 || f >= fps {
197        bail!("frame number out of range for {fps}fps: {f}");
198    }
199
200    Ok((h, m, s, f))
201}
202
203fn scale_frames(frames: i64, from_fps: i64, to_fps: i64) -> Result<i64> {
204    if frames < 0 {
205        bail!("frames must be non-negative, got {frames}");
206    }
207
208    let from = u128::try_from(from_fps).context("from_fps")?;
209    let to = u128::try_from(to_fps).context("to_fps")?;
210    let n = u128::try_from(frames).context("frames")?;
211
212    let num = n.checked_mul(to).context("scale overflow")?;
213    let half = from / 2;
214    let scaled = num
215        .checked_add(half)
216        .context("scale overflow")?
217        .checked_div(from)
218        .context("division by from_fps failed")?;
219
220    i64::try_from(scaled).context("scaled frame count did not fit into i64")
221}
222
223#[cfg(test)]
224#[allow(
225    clippy::panic,
226    clippy::expect_used,
227    clippy::unwrap_used,
228    clippy::unwrap_in_result,
229    clippy::panic_in_result_fn,
230    clippy::indexing_slicing,
231    clippy::arithmetic_side_effects,
232    reason = "Standard repository test boilerplate"
233)]
234mod tests {
235    use ctb_utilities::anyhow::ensure;
236
237    use super::*;
238
239    #[crate::ctb_test]
240    fn tcframes_and_timecode_roundtrip() -> Result<()> {
241        let f = tcframes("01:02:03:04", 24)?;
242        let expected = (3600 + 2 * 60 + 3) * 24 + 4;
243        ensure!(f == expected);
244
245        ensure!(timecode(f, 24)? == "01:02:03:04");
246        Ok(())
247    }
248
249    #[crate::ctb_test]
250    fn tcadd_outcode_and_tcdiff() -> Result<()> {
251        ensure!(tcadd("00:00:00:00", 1, 24)? == "00:00:00:01");
252        ensure!(outcode("00:00:00:23", 24)? == "00:00:01:00");
253
254        // Inclusive diff: same => 1
255        ensure!(tcdiff("00:00:00:00", "00:00:00:00", 24, 0)? == 1);
256        ensure!(tcdiff("00:00:00:00", "00:00:00:01", 24, 0)? == 2);
257
258        // EDL/exclusive: out - in
259        ensure!(tcdiff("00:00:00:00", "00:00:00:01", 24, 1)? == 1);
260        Ok(())
261    }
262
263    #[crate::ctb_test]
264    fn tc_rate_conversions_are_scaled() -> Result<()> {
265        // 00:00:01:12 at 24fps => 36 frames => 1.5s.
266        // At 30fps, 1.5s => 45 frames => 00:00:01:15.
267        ensure!(tc24to30("00:00:01:12")? == "00:00:01:15");
268        ensure!(tc30to24("00:00:01:15")? == "00:00:01:12");
269        Ok(())
270    }
271}