diff --git a/Cargo.toml b/Cargo.toml index 1d38d1c..b280adf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,7 +19,5 @@ tokio = { version = "1", features = ["full"] } clap = { version = "4.4", features = ["derive"] } log = { version = "0.4", features = ["std"] } daemonize = "0.5.0" -num-rational = "0.4" -num-traits = "0.2" diff --git a/src/api.rs b/src/api.rs index a622a0b..3917815 100644 --- a/src/api.rs +++ b/src/api.rs @@ -11,8 +11,6 @@ use std::sync::{Arc, Mutex}; use crate::config::{self, Config}; use crate::sync_logic::{self, LtcState}; use crate::system; -use num_rational::Ratio; -use num_traits::ToPrimitive; // Data structure for the main status response #[derive(Serialize, Deserialize)] @@ -50,7 +48,7 @@ async fn get_status(data: web::Data) -> impl Responder { format!("{:02}:{:02}:{:02}:{:02}", f.hours, f.minutes, f.seconds, f.frames) }); let frame_rate = state.latest.as_ref().map_or("…".to_string(), |f| { - format!("{:.2}fps", f.frame_rate.to_f64().unwrap_or(0.0)) + format!("{:.2}fps", f.frame_rate) }); let now_local = Local::now(); @@ -66,9 +64,8 @@ async fn get_status(data: web::Data) -> impl Responder { let avg_delta = state.get_ewma_clock_delta(); let mut delta_frames = 0; if let Some(frame) = &state.latest { - let delta_ms_ratio = Ratio::new(avg_delta, 1); - let frames_ratio = delta_ms_ratio * frame.frame_rate / Ratio::new(1000, 1); - delta_frames = frames_ratio.round().to_integer(); + let frame_ms = 1000.0 / frame.frame_rate; + delta_frames = ((avg_delta as f64 / frame_ms).round()) as i64; } let sync_status = sync_logic::get_sync_status(avg_delta, &config); @@ -242,7 +239,7 @@ mod tests { minutes: 2, seconds: 3, frames: 4, - frame_rate: Ratio::new(25, 1), + frame_rate: 25.0, timestamp: Utc::now(), }), lock_count: 10, diff --git a/src/serial_input.rs b/src/serial_input.rs index b65cd5f..10c3626 100644 --- a/src/serial_input.rs +++ b/src/serial_input.rs @@ -60,7 +60,6 @@ mod tests { use super::*; use std::sync::mpsc; use crate::sync_logic::LtcState; - use num_rational::Ratio; use regex::Regex; fn get_ltc_regex() -> Regex { @@ -120,7 +119,7 @@ mod tests { assert_eq!(st.free_count, 1); let received_frame = rx.try_recv().unwrap(); assert_eq!(received_frame.status, "FREE"); - assert_eq!(received_frame.frame_rate, Ratio::new(30000, 1001)); + assert_eq!(received_frame.frame_rate, 29.97); } #[test] diff --git a/src/sync_logic.rs b/src/sync_logic.rs index 630e879..a05464c 100644 --- a/src/sync_logic.rs +++ b/src/sync_logic.rs @@ -1,22 +1,10 @@ use crate::config::Config; use chrono::{DateTime, Local, Timelike, Utc}; -use num_rational::Ratio; use regex::Captures; use std::collections::VecDeque; const EWMA_ALPHA: f64 = 0.1; -fn get_frame_rate_ratio(rate_str: &str) -> Option> { - match rate_str { - "23.98" => Some(Ratio::new(24000, 1001)), - "24.00" => Some(Ratio::new(24, 1)), - "25.00" => Some(Ratio::new(25, 1)), - "29.97" => Some(Ratio::new(30000, 1001)), - "30.00" => Some(Ratio::new(30, 1)), - _ => None, - } -} - #[derive(Clone, Debug)] pub struct LtcFrame { pub status: String, @@ -24,7 +12,7 @@ pub struct LtcFrame { pub minutes: u32, pub seconds: u32, pub frames: u32, - pub frame_rate: Ratio, + pub frame_rate: f64, pub timestamp: DateTime, // arrival stamp } @@ -36,7 +24,7 @@ impl LtcFrame { minutes: caps[3].parse().ok()?, seconds: caps[4].parse().ok()?, frames: caps[5].parse().ok()?, - frame_rate: get_frame_rate_ratio(&caps[6])?, + frame_rate: caps[6].parse().ok()?, timestamp, }) } @@ -141,9 +129,8 @@ impl LtcState { /// Convert average jitter into frames (rounded). pub fn average_frames(&self) -> i64 { if let Some(frame) = &self.latest { - let jitter_ms_ratio = Ratio::new(self.average_jitter(), 1); - let frames_ratio = jitter_ms_ratio * frame.frame_rate / Ratio::new(1000, 1); - frames_ratio.round().to_integer() + let ms_per_frame = 1000.0 / frame.frame_rate; + (self.average_jitter() as f64 / ms_per_frame).round() as i64 } else { 0 } @@ -173,9 +160,9 @@ impl LtcState { pub fn get_sync_status(delta_ms: i64, config: &Config) -> &'static str { if config.timeturner_offset.is_active() { "TIMETURNING" - } else if delta_ms.abs() <= 8 { + } else if delta_ms.abs() <= 1 { "IN SYNC" - } else if delta_ms > 10 { + } else if delta_ms > 2 { "CLOCK AHEAD" } else { "CLOCK BEHIND" @@ -205,7 +192,7 @@ mod tests { minutes: m, seconds: s, frames: 0, - frame_rate: Ratio::new(25, 1), + frame_rate: 25.0, timestamp: Utc::now(), } } diff --git a/src/system.rs b/src/system.rs index 7d089e6..c15e452 100644 --- a/src/system.rs +++ b/src/system.rs @@ -1,7 +1,6 @@ use crate::config::Config; use crate::sync_logic::LtcFrame; -use chrono::{DateTime, Duration as ChronoDuration, Local, TimeZone}; -use num_rational::Ratio; +use chrono::{DateTime, Duration as ChronoDuration, Local, NaiveTime, TimeZone}; use std::process::Command; /// Check if Chrony is active @@ -40,32 +39,11 @@ pub fn ntp_service_toggle(start: bool) { pub fn calculate_target_time(frame: &LtcFrame, config: &Config) -> DateTime { let today_local = Local::now().date_naive(); + let ms = ((frame.frames as f64 / frame.frame_rate) * 1000.0).round() as u32; + let timecode = NaiveTime::from_hms_milli_opt(frame.hours, frame.minutes, frame.seconds, ms) + .expect("Invalid LTC timecode"); - // Total seconds from timecode components - let timecode_secs = - frame.hours as i64 * 3600 + frame.minutes as i64 * 60 + frame.seconds as i64; - - // Total duration in seconds as a rational number, including frames - let total_duration_secs = - Ratio::new(timecode_secs, 1) + Ratio::new(frame.frames as i64, 1) / frame.frame_rate; - - // For fractional frame rates (23.98, 29.97), timecode runs slower than wall clock. - // We need to scale the timecode duration up to get wall clock time. - // The scaling factor is 1001/1000. - let scaled_duration_secs = if *frame.frame_rate.denom() == 1001 { - total_duration_secs * Ratio::new(1001, 1000) - } else { - total_duration_secs - }; - - // Convert to milliseconds - let total_ms = (scaled_duration_secs * Ratio::new(1000, 1)) - .round() - .to_integer(); - - let naive_midnight = today_local.and_hms_opt(0, 0, 0).unwrap(); - let naive_dt = naive_midnight + ChronoDuration::milliseconds(total_ms); - + let naive_dt = today_local.and_time(timecode); let mut dt_local = Local .from_local_datetime(&naive_dt) .single() @@ -78,8 +56,7 @@ pub fn calculate_target_time(frame: &LtcFrame, config: &Config) -> DateTime LtcFrame { @@ -196,7 +172,7 @@ mod tests { minutes: m, seconds: s, frames: f, - frame_rate: Ratio::new(25, 1), + frame_rate: 25.0, timestamp: Utc::now(), } } diff --git a/src/ui.rs b/src/ui.rs index 5854f4a..b36e9e3 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -19,11 +19,9 @@ use crossterm::{ }; use crate::config::Config; +use get_if_addrs::get_if_addrs; use crate::sync_logic::{get_jitter_status, get_sync_status, LtcState}; use crate::system; -use get_if_addrs::get_if_addrs; -use num_rational::Ratio; -use num_traits::ToPrimitive; pub fn start_ui( @@ -84,9 +82,8 @@ pub fn start_ui( if last_delta_update.elapsed() >= Duration::from_secs(1) { cached_delta_ms = avg_delta; if let Some(frame) = &state.lock().unwrap().latest { - let delta_ms_ratio = Ratio::new(avg_delta, 1); - let frames_ratio = delta_ms_ratio * frame.frame_rate / Ratio::new(1000, 1); - cached_delta_frames = frames_ratio.round().to_integer(); + let frame_ms = 1000.0 / frame.frame_rate; + cached_delta_frames = ((avg_delta as f64 / frame_ms).round()) as i64; } else { cached_delta_frames = 0; } @@ -107,7 +104,7 @@ pub fn start_ui( None => "LTC Timecode : …".to_string(), }; let fr_str = match opt { - Some(f) => format!("Frame Rate : {:.2}fps", f.frame_rate.to_f64().unwrap_or(0.0)), + Some(f) => format!("Frame Rate : {:.2}fps", f.frame_rate), None => "Frame Rate : …".to_string(), }; diff --git a/timeturner.py b/timeturner.py index 49fe40b..92f8cb2 100644 --- a/timeturner.py +++ b/timeturner.py @@ -9,11 +9,10 @@ import threading import queue import json from collections import deque -from fractions import Fraction SERIAL_PORT = None BAUD_RATE = 115200 -FRAME_RATE = Fraction(25, 1) +FRAME_RATE = 25.0 CONFIG_PATH = "config.json" sync_pending = False @@ -31,14 +30,6 @@ sync_enabled = False last_match_check = 0 timecode_match_status = "UNKNOWN" -def framerate_str_to_fraction(s): - if s == "23.98": return Fraction(24000, 1001) - if s == "24.00": return Fraction(24, 1) - if s == "25.00": return Fraction(25, 1) - if s == "29.97": return Fraction(30000, 1001) - if s == "30.00": return Fraction(30, 1) - return None - def load_config(): global hardware_offset_ms try: @@ -59,16 +50,13 @@ def parse_ltc_line(line): if not match: return None status, hh, mm, ss, ff, fps = match.groups() - rate = framerate_str_to_fraction(fps) - if not rate: - return None return { "status": status, "hours": int(hh), "minutes": int(mm), "seconds": int(ss), "frames": int(ff), - "frame_rate": rate + "frame_rate": float(fps) } def serial_thread(port, baud, q): @@ -166,7 +154,7 @@ def run_curses(stdscr): parsed, arrival_time = latest_ltc stdscr.addstr(3, 2, f"LTC Status : {parsed['status']}") stdscr.addstr(4, 2, f"LTC Timecode : {parsed['hours']:02}:{parsed['minutes']:02}:{parsed['seconds']:02}:{parsed['frames']:02}") - stdscr.addstr(5, 2, f"Frame Rate : {float(FRAME_RATE):.2f}fps") + stdscr.addstr(5, 2, f"Frame Rate : {FRAME_RATE:.2f}fps") stdscr.addstr(6, 2, f"System Clock : {format_time(get_system_time())}") if ltc_locked and sync_enabled and offset_history: