Skip to content

Effort free video editing!

4.8 KB
Raw Blame
## Values written on the command line and in timeline files: numbers with
## units, thresholds, bitrates and times.

import std/[math, strformat, strutils]
import ../lib/[dnorm16, numparse, timeunit]
import ../log
import ./timecode

# Times stay well inside int64 so arithmetic on them can't overflow; "end"
# is the largest.
const timeSpan = float64(1'i64 shl 62)
const endFrames = 0x3FFFFFFFFFFFFFFF'i64

proc splitNumStr*(val: string): (float64, string) =
  var index = 0
  for char in val:
    if char notin "0123456789_ .-":
      break
    index += 1
  let (num, unit) = (val[0 ..< index], val[index .. ^1])
  var floatNum: float
  if not toFloat(num.replace(" ", ""), floatNum):
    error &"Invalid number: '{val}'"
  (floatNum, unit)

proc parseThres*(val: string): Unorm16 =
  let (num, unit) = splitNumStr(val)
  var r: float32
  if unit == "%":
    r = float32(num / 100)
  elif unit == "dB":
    r = float32(pow(10, num / 20))
  elif unit == "":
    r = float32(num)
  else:
    error &"Unknown unit: {unit}"
  if r < 0 or r > 1:
    error &"Threshold not in range: {val} ({r})"
  return toUnorm16(r)

proc parseBitrate*(input: string): int =
  if input == "auto":
    return -1

  let (val, unit) = splitNumStr(input)
  let scale =
    if unit.toLowerAscii() == "k": 1000.0
    elif unit == "M": 1_000_000.0
    elif unit == "G": 1_000_000_000.0
    elif unit == "": 1.0
    else: error &"Unknown bitrate: {input}"
  let bits = val * scale
  if not (bits >= 0 and bits < high(int).float64):  # Guards NaN
    error &"Bitrate out of range: {input}"
  return int(bits)

proc parseTimeSimple*(val: string): TimeSpec =
  let (num, unit) = splitNumStr(val)
  template checked(x: float64): int64 =
    let f = x
    if not (f > -timeSpan and f < timeSpan):  # Guards NaN
      error &"'{val}': Time is out of range"
    f.int64
  var tu: TimeUnit
  if not parseTimeUnit(unit, tu):
    error &"'{val}': Time format got unknown unit: `{unit}`"
  if tu != tuFrames:
    return millis(checked(round(num * 1000 * tu.seconds)))

  if num != trunc(num):
    if unit == "":
      error &"'{val}': A time without a unit is a frame count, so it must be " &
        &"whole. For seconds, write '{val}s'"
    error &"'{val}': A frame count must be whole"
  return frames(checked(num))

proc parseClock(val: string): TimeSpec =
  ## `HH:MM:SS:FF` timecode (`;FF` for drop frame), or `MM:SS` and
  ## `HH:MM:SS` clock time with optional decimal seconds. MM:SS:FF isn't
  ## taken: it reads the same as HH:MM:SS.
  let neg = val.startsWith("-")
  let body = (if neg: val[1 .. ^1] else: val)
  var seps = 0
  for c in body:
    if c in {':', ';'}: inc seps
  if seps == 3:
    let semi = body.find(';')
    if '.' in body or ',' in body or semi >= 0 and semi < body.rfind(':'):
      error &"'{val}': Timecode is HH:MM:SS:FF, or HH:MM:SS;FF for drop frame"
    var tc: Timecode
    if not parseTimecode(body, tc):
      error &"'{val}': Timecode is HH:MM:SS:FF, or HH:MM:SS;FF for drop frame"
    if tc.m >= 60 or tc.s >= 60:
      error &"'{val}': Timecode minutes and seconds must be under 60"
    return TimeSpec(kind: tkTimecode, tc: tc, neg: neg)
  if seps notin 1..2 or ';' in body:
    error &"'{val}': Write a time as MM:SS or HH:MM:SS, or timecode as HH:MM:SS:FF"
  let parts = body.split(':')
  var total = 0.0
  for i, part in parts:
    var dots = 0
    for c in part:
      if c == '.': inc dots
      elif c notin Digits: dots = 2
    if part.len == 0 or dots > 1 or dots == 1 and i < parts.high:
      error &"'{val}': Write a time as MM:SS or HH:MM:SS, or timecode as HH:MM:SS:FF"
    var x: float
    discard toFloat(part, x)
    if i > 0 and x >= 60:
      error &"'{val}': Minutes and seconds must be under 60"
    total = total * 60 + x
  let ms = round(total * 1000)
  if not (ms < timeSpan):
    error &"'{val}': Time is out of range"
  millis(if neg: -ms.int64 else: ms.int64)

proc parseTime*(val: string): TimeSpec =
  if val == "start":
    return frames(0)
  if val == "end":
    return frames(endFrames)
  if ':' in val or ';' in val:
    return parseClock(val)
  return parseTimeSimple(val)

proc toTb*(val: TimeSpec, tb: float64): int =
  case val.kind
  of tkFrames:
    int(val.n)
  of tkMillis:
    # A time that far out is past "end" anyway; it saturates.
    let f = round(val.n.float64 / 1000.0 * tb)
    if not (f > low(int).float64 and f < high(int).float64):
      return (if f < 0: low(int) else: high(int))
    f.int
  of tkTimecode:
    # Timecode counts whole frames a second: 30 for 29.97.
    let base = max(1'i64, int64(ceil(tb - 1e-9)))
    if val.tc.f >= base:
      error &"Timecode frame {val.tc.f} is past the timeline's {base} frames a second"
    let ntsc = base mod 30 == 0 and abs(tb - base.float64) > 1e-6
    if val.tc.drop and not ntsc:
      error "Drop-frame timecode (with ';') needs a 29.97 or 59.94 fps timeline"
    let n = val.tc.toFrames(base, val.tc.drop)
    int(if val.neg: -n else: n)