Skip to content

Effort free video editing!

871 B
Raw Blame
import std/[math, strformat]

type Code* = enum
  standard, ass, display

func toTimecode*(secs: float, fmt: Code): string =
  var sign = ""
  var seconds = secs
  if seconds < 0:
    sign = "-"
    seconds = -seconds

  # Quantize to the format's precision before splitting into h/m/s, so a
  # seconds field that would format as 60 carries into the minute
  # (59.9996 -> 00:01:00.000, not 00:00:60.000).
  let quantum = case fmt
    of standard: 1000.0
    of ass: 100.0
    of display: 1.0
  let totalSeconds = round(seconds * quantum) / quantum
  let mFloat = totalSeconds / 60.0
  let hFloat = mFloat / 60.0

  let h = int(hFloat)
  let m = int(mFloat) mod 60
  let s = totalSeconds mod 60.0

  case fmt:
  of standard:
    &"{sign}{h:02d}:{m:02d}:{s:06.3f}"
  of ass:
    &"{sign}{h:d}:{m:02d}:{s:05.2f}"
  of display:
    &"{sign}{h:d}:{m:02d}:{s.round.int:02d}"