ctb_formats_pan/time/
film.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//! Film feet+frames helpers for 35mm 4-perf (16 frames per foot).
27
28#[expect(unused_imports, reason = "imported module dependencies")]
29use crate::utilities::*;
30
31const FRAMES_PER_FOOT_35MM: i64 = 16;
32
33/// Formats a frame count as `feet+frames`.
34pub fn feetandframes(frames: i64) -> Result<String> {
35    if frames < 0 {
36        bail!("frames must be non-negative, got {frames}");
37    }
38
39    let feet = frames.div_euclid(FRAMES_PER_FOOT_35MM);
40    let fr = frames.rem_euclid(FRAMES_PER_FOOT_35MM);
41    Ok(format!("{feet}+{fr:02}"))
42}
43
44/// Parses a `feet+frames` keycode into total frames.
45pub fn kcframes(feetplusframes: &str) -> Result<i64> {
46    let (feet, fr) = parse_feet_plus_frames(feetplusframes)?;
47    let secs = feet
48        .checked_mul(FRAMES_PER_FOOT_35MM)
49        .context("feet overflow")?
50        .checked_add(fr)
51        .context("frame overflow")?;
52    Ok(secs)
53}
54
55/// Adds `offset` frames to a keycode string.
56pub fn kcadd(keycode: &str, offset: i64) -> Result<String> {
57    let base = kcframes(keycode)?;
58    let out = base.checked_add(offset).context("frame overflow")?;
59    if out < 0 {
60        bail!("resulting keycode would be negative ({out})");
61    }
62    feetandframes(out)
63}
64
65/// Returns the inclusive frame count between two keycodes.
66pub fn kcdiff(incode: &str, outcode: &str) -> Result<i64> {
67    let a = kcframes(incode)?;
68    let b = kcframes(outcode)?;
69    let diff = b.checked_sub(a).context("frame overflow")?;
70
71    // Inclusive counts: same keycode => 1 frame.
72    if diff >= 0 {
73        diff.checked_add(1).context("frame overflow")
74    } else {
75        diff.checked_sub(1).context("frame overflow")
76    }
77}
78
79/// Returns the last keycode given a start and inclusive length.
80pub fn kcoutfromlength(key: &str, offset: i64) -> Result<String> {
81    if offset <= 0 {
82        bail!("length must be positive, got {offset}");
83    }
84
85    let base = kcframes(key)?;
86    let last = base
87        .checked_add(offset)
88        .context("frame overflow")?
89        .checked_sub(1)
90        .context("frame overflow")?;
91
92    feetandframes(last)
93}
94
95fn parse_feet_plus_frames(s: &str) -> Result<(i64, i64)> {
96    let raw = s.trim();
97    if raw.is_empty() {
98        bail!("empty feet+frames string");
99    }
100
101    let (a, b) = if let Some((l, r)) = raw.split_once('+') {
102        (l, r)
103    } else if let Some((l, r)) = raw.split_once(':') {
104        (l, r)
105    } else if let Some((l, r)) = raw.split_once(' ') {
106        (l, r)
107    } else {
108        bail!("expected feet+frames like \"12+08\", got {raw}");
109    };
110
111    let feet = a.trim().parse::<i64>().context("feet")?;
112    let fr = b.trim().parse::<i64>().context("frames")?;
113
114    if feet < 0 {
115        bail!("feet must be non-negative, got {feet}");
116    }
117    if !(0..FRAMES_PER_FOOT_35MM).contains(&fr) {
118        bail!("frames must be 0..={}, got {fr}", FRAMES_PER_FOOT_35MM - 1);
119    }
120
121    Ok((feet, fr))
122}
123
124#[cfg(test)]
125#[allow(
126    clippy::panic,
127    clippy::expect_used,
128    clippy::unwrap_used,
129    clippy::unwrap_in_result,
130    clippy::panic_in_result_fn,
131    clippy::indexing_slicing,
132    clippy::arithmetic_side_effects,
133    reason = "Standard repository test boilerplate"
134)]
135mod tests {
136    use ctb_utilities::anyhow::ensure;
137
138    use super::*;
139
140    #[crate::ctb_test]
141    fn feet_and_frames_roundtrip() -> Result<()> {
142        ensure!(feetandframes(0)? == "0+00");
143        ensure!(feetandframes(17)? == "1+01");
144
145        ensure!(kcframes("0+00")? == 0);
146        ensure!(kcframes("1+01")? == 17);
147        Ok(())
148    }
149
150    #[crate::ctb_test]
151    fn kc_add_diff_and_out_from_length() -> Result<()> {
152        ensure!(kcadd("1+00", 16)? == "2+00");
153
154        // Inclusive diff: same => 1
155        ensure!(kcdiff("2+00", "2+00")? == 1);
156        ensure!(kcdiff("1+00", "1+01")? == 2);
157
158        // Length N => last = start + (N-1)
159        ensure!(kcoutfromlength("1+00", 1)? == "1+00");
160        ensure!(kcoutfromlength("1+00", 16)? == "1+15");
161        Ok(())
162    }
163}