Skip to content

Effort free video editing!

Split util/fun and move log-free code to src/lib

WyattBluee2e1d8b63b5c
diff --git a/src/cache.nim b/src/cache.nim
index 146fcf1e..0202655f 100644
--- a/src/cache.nim
+++ b/src/cache.nim
@@ -1,7 +1,7 @@
import std/[algorithm, options, os, streams, strformat, strutils, times]
import ./[about, ffmpeg, log]
-import ./lib/[dnorm16, sha]
-import ./util/[fun, rational]
+import ./lib/[dnorm16, paths, sha]
+import ./util/[abspath, rational]
type CacheCodec = enum
ccFloat32 = 0'u8 # raw float32
@@ -22,7 +22,8 @@ proc procTag(path: AbsPath, tb: AVRational, kind, args: string): string =
var ctx = initSha1()
ctx.update(key)
let digest = ctx.finish()
- for i in 0 ..< 8: result.add toHex(digest[i], 2)
+ for i in 0 ..< 8:
+ result.add toHex(digest[i], 2)
result = result.toLowerAscii() & kind
# Levels are cached in their in-memory form (Unorm16 / Snorm16 / float32) and
diff --git a/src/cmds/cache.nim b/src/cmds/cache.nim
index 83d04851..a3ded4fe 100644
--- a/src/cmds/cache.nim
+++ b/src/cmds/cache.nim
@@ -1,20 +1,10 @@
import std/[os, strformat, strutils, terminal]
import ../[about, cli, log]
-import ../util/fun
+import ../lib/[paths, text]
import ./help
assertArgumentOptions(cacheOptions, {})
-func formatBytes(intSize: BiggestInt): (string, string) =
- if intSize < 1024:
- return ($intSize, "B")
- var size = intSize.float / 1024.0
- for unit in ["KiB", "MiB", "GiB", "TiB"]:
- if size < 1024.0:
- return (&"{size:.2f}", unit)
- size = size / 1024.0
- return (&"{size:.2f}", "PiB")
-
proc main*(args: seq[string]) =
var positionals: seq[string] = @[]
diff --git a/src/cmds/help.nim b/src/cmds/help.nim
index 94288bff..827ac6cc 100644
--- a/src/cmds/help.nim
+++ b/src/cmds/help.nim
@@ -1,6 +1,6 @@
import std/[strformat, strutils]
import ../[cli, log]
-import ../util/[fun, term]
+import ../lib/[term, text]
proc printHelp*(usage: string, opts: seq[OptDef]) {.noreturn.} =
let termWidth = max(terminalWidth(), 40)
diff --git a/src/cmds/info.nim b/src/cmds/info.nim
index fcf2f457..9b0f81d2 100644
--- a/src/cmds/info.nim
+++ b/src/cmds/info.nim
@@ -1,7 +1,7 @@
import std/[json, sets, strformat, strutils, tables]
import ../[av, cli, ffmpeg, log, media]
-import ../lib/lang
-import ../util/[fun, rational]
+import ../lib/[aspect, lang]
+import ../util/rational
import ./help
proc genericTrack(lang: Lang, bitrate: int64) =
diff --git a/src/cmds/whisper.nim b/src/cmds/whisper.nim
index ac046f99..b56c7d83 100644
--- a/src/cmds/whisper.nim
+++ b/src/cmds/whisper.nim
@@ -1,7 +1,7 @@
import std/[os, strformat, strutils]
import ../[av, cli, ffmpeg, log, transcribe]
import ../lib/dnorm16
-import ../util/fun
+import ../util/parse
import ./help
when defined(macosx) or defined(windows) or
(defined(linux) and not defined(emscripten)):
diff --git a/src/conductor.nim b/src/conductor.nim
index 8fae6d93..1e4b98d6 100644
--- a/src/conductor.nim
+++ b/src/conductor.nim
@@ -3,9 +3,9 @@ from std/math import round
import ./[action, av, edit, ffmpeg, license, log, media, stats, timeline]
import ./exports/[drops, edl, fcp11, fcp7, json, kdenlive, otio, shotcut]
import ./imports/[edl, fcp11, fcp7, json]
-import ./lib/[editutil, lang]
+import ./lib/[clock, editutil, lang, paths]
import ./render/[format, subtitle]
-import ./util/[bar, color, fun, rational, rules]
+import ./util/[bar, color, parse, rational, rules, timecode]
when not defined(emscripten):
from std/browsers import openDefaultBrowser
diff --git a/src/edit.nim b/src/edit.nim
index fab943ea..fe13cf5d 100644
--- a/src/edit.nim
+++ b/src/edit.nim
@@ -2,7 +2,7 @@ import std/[math, options, os, sequtils, strformat, strutils]
import ./[av, editexpr, editlexer, editparse, ffmpeg, log]
import ./analyze/[audio, blackdetect, motion, subtitle]
import ./lib/[audioutil, dnorm16, suggest, tinyre, wordre]
-import ./util/[bar, fun, rational]
+import ./util/[bar, parse, rational]
type
NormSymbol = enum
diff --git a/src/exports/edl.nim b/src/exports/edl.nim
index bc7e13a9..f81133df 100644
--- a/src/exports/edl.nim
+++ b/src/exports/edl.nim
@@ -9,7 +9,8 @@
import std/[algorithm, os, strformat, strutils, tables]
from std/math import round
import ../[log, timeline]
-import ../util/[fun, speedmap, timecode]
+import ../lib/paths
+import ../util/[speedmap, timecode]
type
Channel = enum
diff --git a/src/exports/fcp11.nim b/src/exports/fcp11.nim
index c121ff9d..cbe5b9d1 100644
--- a/src/exports/fcp11.nim
+++ b/src/exports/fcp11.nim
@@ -1,8 +1,8 @@
import std/[algorithm, strformat, strutils, tables]
from std/math import ceil, round
import ../[ffmpeg, log, media, timeline]
-import ../lib/lang
-import ../util/[fun, rational, speedmap, xml]
+import ../lib/[lang, paths]
+import ../util/[abspath, rational, speedmap, xml]
#[
Export a FCPXML 11 file readable with Final Cut Pro 10.6.8 or later.
diff --git a/src/exports/fcp7.nim b/src/exports/fcp7.nim
index a7f693df..035aa213 100644
--- a/src/exports/fcp7.nim
+++ b/src/exports/fcp7.nim
@@ -1,7 +1,8 @@
import std/[os, sets, strformat, tables]
from std/math import ceil, round
import ../[action, ffmpeg, log, media, timeline]
-import ../util/[fun, rational, speedmap, xml]
+import ../lib/paths
+import ../util/[rational, speedmap, xml]
when defined(windows):
import std/strutils
diff --git a/src/exports/kdenlive.nim b/src/exports/kdenlive.nim
index 4f29e1ae..de203709 100644
--- a/src/exports/kdenlive.nim
+++ b/src/exports/kdenlive.nim
@@ -1,7 +1,7 @@
import std/[json, os, sequtils, strformat, strutils, sysrand, tables]
import ../[action, log, media, timeline]
-import ../lib/dnorm16
-import ../util/[color, fun, rational, xml]
+import ../lib/[aspect, clock, dnorm16]
+import ../util/[color, rational, xml]
import ./mlt
proc genUuid*(): string =
diff --git a/src/exports/otio.nim b/src/exports/otio.nim
index 2fb7646c..80b1455a 100644
--- a/src/exports/otio.nim
+++ b/src/exports/otio.nim
@@ -1,7 +1,8 @@
import std/[json, os, sets, strutils, tables]
from std/math import round, hypot, ceil, sin, cos, PI
import ../[action, ffmpeg, log, media, timeline]
-import ../util/[color, fun, rational]
+import ../util/[abspath, color, rational]
+import ../lib/paths
#[
OpenTimelineIO (.otio) export, compatible with Adobe Premiere Pro.
diff --git a/src/exports/shotcut.nim b/src/exports/shotcut.nim
index ec7829ad..eabe925a 100644
--- a/src/exports/shotcut.nim
+++ b/src/exports/shotcut.nim
@@ -1,7 +1,7 @@
import std/[sequtils, strformat, strutils]
import ../[action, ffmpeg, log, timeline]
-import ../lib/dnorm16
-import ../util/[color, fun, rational, xml]
+import ../lib/[aspect, clock, dnorm16, paths]
+import ../util/[color, rational, xml]
import ./mlt
diff --git a/src/imports/fcp11.nim b/src/imports/fcp11.nim
index 6fe07357..01d6e43c 100644
--- a/src/imports/fcp11.nim
+++ b/src/imports/fcp11.nim
@@ -4,8 +4,8 @@
import std/[algorithm, math, os, strformat, strutils, tables]
import ../[action, av, log, timeline]
-import ../lib/lang
-import ../util/[color, fun, rational, speedmap, xml]
+import ../lib/[audioutil, lang, paths]
+import ../util/[color, rational, speedmap, xml]
# Tags common in FCPXML, so the parsed tree can share their strings.
const fcp11Tags = ["fcpxml", "resources", "format", "asset", "media-rep",
diff --git a/src/imports/fcp7.nim b/src/imports/fcp7.nim
index bf8a9b97..128f90fb 100644
--- a/src/imports/fcp7.nim
+++ b/src/imports/fcp7.nim
@@ -1,7 +1,8 @@
import std/[algorithm, sequtils, strformat, strutils, tables]
from std/math import classify, fcInf, fcNan, fcNegInf, round
import ../[action, ffmpeg, log, timeline]
-import ../util/[color, fun, rational, speedmap, xml]
+import ../lib/[audioutil, paths]
+import ../util/[color, rational, speedmap, xml]
# Tags common in FCP7 XML, so the parsed tree can share their strings.
const fcp7Tags = ["xmeml", "sequence", "media", "video", "audio", "track",
diff --git a/src/imports/json.nim b/src/imports/json.nim
index 6d677a5d..f64abbdf 100644
--- a/src/imports/json.nim
+++ b/src/imports/json.nim
@@ -1,7 +1,7 @@
import std/[json, strformat]
import ../[action, av, ffmpeg, log, media, timeline]
-import ../lib/lang
-import ../util/[color, fun, rational]
+import ../lib/[audioutil, lang]
+import ../util/[color, rational]
proc parseActionOrErr(val: string): Action {.raises: [AutoEditorError].} =
try: parseAction(val)
diff --git a/src/lib/aspect.nim b/src/lib/aspect.nim
new file mode 100644
index 00000000..651a06f9
--- /dev/null
+++ b/src/lib/aspect.nim
@@ -0,0 +1,42 @@
+import std/math
+
+const
+ commonAspectRatios = [
+ (1, 1), (5, 4), (4, 3), (3, 2), (16, 10), (16, 9), (2, 1), (64, 27)
+ ]
+ # Max drift, in stored pixels, between a dimension and what a common ratio
+ # would produce for us to treat the difference as codec-friendly rounding
+ # rather than a deliberate ratio. Absolute (not relative) so the snap stays
+ # tight at high resolutions where a percentage would be many pixels wide.
+ aspectSnapDrift = 2.0
+
+func aspectRatio*(width, height: int, sarNum = 1, sarDen = 1): tuple[w, h: int] =
+ if width <= 0 or height <= 0:
+ return (0, 0)
+
+ # Fold the sample (pixel) aspect ratio into the dimensions so anamorphic video
+ # reports its true display aspect ratio, the way ffmpeg's DAR does.
+ let
+ sn = max(sarNum, 1)
+ sd = max(sarDen, 1)
+ dispW = width * sn
+ dispH = height * sd
+ c = gcd(dispW, dispH)
+ result = (dispW div c, dispH div c)
+
+ # A clean, small reduction is already a meaningful ratio (16:9, 4:3, 8:5...).
+ if max(result.w, result.h) <= 50:
+ return
+
+ let (w, h) = (width.float, height.float)
+ var bestDrift = aspectSnapDrift
+ for (cw, ch) in commonAspectRatios:
+ for (a, b) in [(cw, ch), (ch, cw)]:
+ # Stored dimensions that would yield this display ratio for the given SAR.
+ let
+ ta = float(a * sd) # storage-width units
+ tb = float(b * sn) # storage-height units
+ drift = max(abs(w - h * ta / tb), abs(h - w * tb / ta))
+ if drift < bestDrift:
+ bestDrift = drift
+ result = (a, b)
diff --git a/src/lib/audioutil.nim b/src/lib/audioutil.nim
index a0f030c3..64947fd1 100644
--- a/src/lib/audioutil.nim
+++ b/src/lib/audioutil.nim
@@ -23,3 +23,7 @@ func audioChannelName*(code: string): string {.raises: [].} =
for (friendly, c) in audioChannelNames:
if code == c:
return friendly
+
+const
+ minSampleRate* = 100
+ maxSampleRate* = 768_000 ## the highest PCM rate in use
diff --git a/src/lib/base64url.nim b/src/lib/base64url.nim
new file mode 100644
index 00000000..fcd8fd52
--- /dev/null
+++ b/src/lib/base64url.nim
@@ -0,0 +1,7 @@
+import std/[base64, strutils]
+
+func b64urlDecode*(s: string): seq[byte] =
+ var padded = s.replace('-', '+').replace('_', '/')
+ while padded.len mod 4 != 0:
+ padded &= "="
+ cast[seq[byte]](base64.decode(padded))
diff --git a/src/lib/clock.nim b/src/lib/clock.nim
new file mode 100644
index 00000000..e2f8122d
--- /dev/null
+++ b/src/lib/clock.nim
@@ -0,0 +1,34 @@
+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}"
diff --git a/src/lib/lang.nim b/src/lib/lang.nim
index a3c05914..7785aaf3 100644
--- a/src/lib/lang.nim
+++ b/src/lib/lang.nim
@@ -65,17 +65,21 @@ func toLang*(a: string): Lang =
## The ISO 639-2/T code for the language `a` starts with, ignoring any
## region subtag as in "en-US": "eng". "und" when it isn't a language code.
var n = 0
- while n < a.len and a[n] notin {'-', '_'}: inc n
+ while n < a.len and a[n] notin {'-', '_'}:
+ inc n
var code = a[0 ..< n].toLowerAscii
- if n notin 2..3 or not code.allCharsInSet({'a'..'z'}): return undLang
+ if n notin 2..3 or not code.allCharsInSet({'a'..'z'}):
+ return undLang
if n == 2:
let i = iso639_1.binarySearch(code, cmpKey)
- if i < 0: return undLang
+ if i < 0:
+ return undLang
code = iso639_1[i][1]
else:
let i = iso639_2b.binarySearch(code, cmpKey)
if i >= 0: code = iso639_2b[i][1]
- for i in 0 ..< 3: result[i] = code[i]
+ for i in 0 ..< 3:
+ result[i] = code[i]
iterator iso639_1Codes*(lang: Lang): string =
## The ISO 639-1 codes for `lang`, deprecated ones like "iw" included.
diff --git a/src/lib/paths.nim b/src/lib/paths.nim
new file mode 100644
index 00000000..2c1a38df
--- /dev/null
+++ b/src/lib/paths.nim
@@ -0,0 +1,101 @@
+import std/strutils
+from std/uri import decodeUrl
+when defined(windows):
+ from std/os import splitFile
+
+type AbsPath* = distinct string
+ ## A filesystem path known to be absolute. `absPath` (in util/abspath) is the
+ ## only constructor, so consumers can rely on the invariant (and stay `func`).
+func `$`*(path: AbsPath): string {.borrow.}
+
+func pathToUri*(path: AbsPath): string {.raises: [].} =
+ ## file:// URL for a path. Bytes outside the RFC 3986 path set (spaces,
+ ## '#', '%', non-ASCII, ...) are percent-encoded.
+ var p = $path
+ when defined(windows):
+ p = p.replace('\\', '/')
+ result = "file:///"
+ else:
+ result = "file://"
+ for c in p:
+ if c in {'a'..'z', 'A'..'Z', '0'..'9', '-', '.', '_', '~', '/', ':'}:
+ result.add c
+ else:
+ result.add '%'
+ result.add toHex(ord(c), 2)
+
+func uriToPath*(uri: string): string {.raises: [].} =
+ ## The path a file:// URL names, decoded; other strings unchanged.
+ var path = uri
+ if path.startsWith("file://localhost/"):
+ # Windows-style: file://localhost/C:/... -> C:/...
+ if path.len > 18 and path[18] == ':':
+ path = path[17..^1]
+ else:
+ path = path[16..^1]
+ elif path.startsWith("file://"):
+ # Windows-style: file:///C:/... -> C:/...
+ if path.len > 9 and path[9] == ':':
+ path = path[8..^1]
+ else:
+ # Unix-style: file:///path -> /path
+ path = path[7..^1]
+ else:
+ return uri
+ return decodeUrl(path, decodePlus = false)
+
+when defined(posix):
+ from std/posix import Stat, stat, S_ISREG, S_ISDIR, S_ISFIFO, S_ISSOCK
+
+proc isDevicePath*(path: string): bool {.raises: [].} =
+ ## Whether `path` names something other than a file to create or replace:
+ ## a device (/dev/null), a pipe (/dev/stdout, `>(cmd)`), or a socket. Its
+ ## name is fixed, so nothing may add an extension or derive siblings from it.
+ when defined(windows):
+ let (_, name, _) = splitFile(path)
+ path.startsWith(r"\\.\") or name.toUpperAscii in ["NUL", "CON", "PRN",
+ "AUX", "COM1", "COM2", "COM3", "COM4", "LPT1", "LPT2", "LPT3"]
+ elif defined(posix) and not defined(emscripten):
+ # An alias of an open descriptor (/dev/stdout redirected to a file)
+ # stats as whatever it points at.
+ if path in ["/dev/stdout", "/dev/stderr"] or path.startsWith("/dev/fd/") or
+ path.startsWith("/proc/") and "/fd/" in path:
+ return true
+ var st: Stat
+ stat(path.cstring, st) == 0 and not S_ISREG(st.st_mode) and
+ not S_ISDIR(st.st_mode)
+ else:
+ false
+
+proc isPipePath*(path: string): bool {.raises: [].} =
+ ## Whether writing `path` can't seek back, as a muxer finishing its header
+ ## would.
+ when defined(posix) and not defined(emscripten):
+ var st: Stat
+ stat(path.cstring, st) == 0 and (S_ISFIFO(st.st_mode) or S_ISSOCK(st.st_mode))
+ else:
+ false
+
+func agSplitFile*(path: string): tuple[dir, name, ext: string] =
+ ## Platform-independent splitFile. Treats both '/' and '\' as path separators
+ ## on every OS, so results don't drift between Linux, macOS, and Windows.
+ var namePos = 0
+ var dotPos = 0
+ for i in countdown(path.len - 1, 0):
+ if path[i] == '.' and dotPos == 0:
+ dotPos = i
+ elif path[i] == '/' or path[i] == '\\':
+ if namePos == 0:
+ namePos = i + 1
+ if dotPos > namePos and dotPos < path.len - 1:
+ result.name = substr(path, namePos, dotPos - 1)
+ result.ext = substr(path, dotPos)
+ else:
+ result.name = substr(path, namePos)
+ result.dir = substr(path, 0, max(0, namePos - 2))
+ return
+ if dotPos > 0 and dotPos < path.len - 1:
+ result.name = substr(path, 0, dotPos - 1)
+ result.ext = substr(path, dotPos)
+ else:
+ result.name = path
diff --git a/src/util/term.nim b/src/lib/term.nim
similarity index 100%
rename from src/util/term.nim
rename to src/lib/term.nim
diff --git a/src/lib/text.nim b/src/lib/text.nim
new file mode 100644
index 00000000..1857068b
--- /dev/null
+++ b/src/lib/text.nim
@@ -0,0 +1,70 @@
+import std/[strformat, strutils]
+
+func formatBytes*(intSize: BiggestInt): (string, string) =
+ if intSize < 1024:
+ return ($intSize, "B")
+ var size = intSize.float / 1024.0
+ for unit in ["KiB", "MiB", "GiB", "TiB"]:
+ if size < 1024.0:
+ return (&"{size:.2f}", unit)
+ size = size / 1024.0
+ return (&"{size:.2f}", "PiB")
+
+func visibleLen(s: string): int =
+ # Count only visible characters, skipping OSC escape sequences (\e]...\e\)
+ var i = 0
+ while i < s.len:
+ if s[i] == '\e' and i + 1 < s.len and s[i + 1] == ']':
+ i += 2
+ while i < s.len:
+ if s[i] == '\e' and i + 1 < s.len and s[i + 1] == '\\':
+ i += 2
+ break
+ i += 1
+ else:
+ result += 1
+ i += 1
+
+func wrapText*(text: string, width, indent: int): string =
+ let text = text.strip(leading = true, trailing = true, chars = {'\n'})
+ if text.len == 0:
+ return ""
+ let indentStr = " ".repeat(indent)
+ var outLines: seq[string] = @[]
+ var isFirst = true
+
+ for line in text.split("\n"):
+ if line.len == 0:
+ outLines.add("")
+ else:
+ # Detect leading whitespace
+ var leadingSpaces = 0
+ for c in line:
+ if c == ' ':
+ leadingSpaces += 1
+ else:
+ break
+ let lineIndent = " ".repeat(leadingSpaces)
+ let content = line[leadingSpaces .. ^1]
+
+ var currentLine = ""
+ for word in content.splitWhitespace():
+ if currentLine.len == 0:
+ currentLine = word
+ elif leadingSpaces + visibleLen(currentLine) + 1 + visibleLen(word) <= width:
+ currentLine &= " " & word
+ else:
+ if isFirst:
+ outLines.add(lineIndent & currentLine)
+ isFirst = false
+ else:
+ outLines.add(indentStr & lineIndent & currentLine)
+ currentLine = word
+ if currentLine.len > 0:
+ if isFirst:
+ outLines.add(lineIndent & currentLine)
+ isFirst = false
+ else:
+ outLines.add(indentStr & lineIndent & currentLine)
+
+ result = outLines.join("\n")
diff --git a/src/license.nim b/src/license.nim
index f7d33748..45697854 100644
--- a/src/license.nim
+++ b/src/license.nim
@@ -1,6 +1,6 @@
import std/[envvars, json, strformat, strutils]
import ./log
-import ./util/fun
+import ./lib/base64url
import ./vendor/libp2p/ed25519
const PUBLIC_KEY_HEX = "aa8512235f1e329522c00b23e473a810a31ec8ee9c727cda91c779c9db6aae0f"
diff --git a/src/log.nim b/src/log.nim
index 15830727..8b6ca6db 100644
--- a/src/log.nim
+++ b/src/log.nim
@@ -1,7 +1,7 @@
import std/[envvars, options, os, strformat, tables, times]
import ./[action, cli, editexpr, ffmpeg]
-import ./lib/transitions
-import ./util/[color, rational, term, timecode]
+import ./lib/[term, transitions]
+import ./util/[color, rational, timecode]
when not defined(emscripten):
import std/strutils
export editexpr, transitions
@@ -23,18 +23,6 @@ type
name*: string
version*: uint8
- TimeKind* = enum
- tkFrames ## whole frames at the timeline's rate
- tkMillis ## milliseconds
- tkTimecode ## SMPTE timecode, counted at the timeline's rate
- TimeSpec* = object
- ## A time as written, made into frames once the timeline's rate is known.
- case kind*: TimeKind
- of tkFrames, tkMillis: n*: int64
- of tkTimecode:
- tc*: Timecode
- neg*: bool
-
func `$`*(kind: ExportKind): string {.raises: [].} =
case kind
of exAuto: ""
@@ -52,20 +40,6 @@ func `$`*(kind: ExportKind): string {.raises: [].} =
of exPremiereOtio: "premiere-otio"
of exEdl: "edl"
-func frames*(n: int64): TimeSpec {.raises: [].} =
- TimeSpec(kind: tkFrames, n: n)
-
-func millis*(n: int64): TimeSpec {.raises: [].} =
- TimeSpec(kind: tkMillis, n: n)
-
-func sign*(t: TimeSpec): int {.raises: [].} =
- case t.kind
- of tkFrames, tkMillis: cmp(t.n, 0'i64)
- of tkTimecode:
- if t.tc.h == 0 and t.tc.m == 0 and t.tc.s == 0 and t.tc.f == 0: 0
- elif t.neg: -1
- else: 1
-
type
NormKind* = enum
nkNull, nkEbu, nkPeak
diff --git a/src/main.nim b/src/main.nim
index 899bef4d..1570b3eb 100644
--- a/src/main.nim
+++ b/src/main.nim
@@ -1,9 +1,9 @@
import std/[options, os, parseutils, sequtils, strformat, strutils]
import ./[about, action, cli, conductor, edit, ffmpeg, license, log]
import ./cmds/[cache, desc, info, levels, subdump, whisper]
-import ./lib/[escape, suggest, tinyre]
+import ./lib/[audioutil, escape, paths, suggest, term, text, tinyre]
import ./render/burnsubs
-import ./util/[color, fun, rational, term]
+import ./util/[color, parse, rational, timecode]
from ./av import codecAlias
when defined(emscripten):
import ./av
diff --git a/src/stats.nim b/src/stats.nim
index 82d61475..149599c3 100644
--- a/src/stats.nim
+++ b/src/stats.nim
@@ -1,8 +1,8 @@
import std/[sets, strformat, strutils, tables]
from std/math import round
import ./[action, av, ffmpeg, log, timeline]
-import ./lib/cliputil
-import ./util/[fun, rational]
+import ./lib/[cliputil, clock]
+import ./util/rational
import ./vendor/csort/csort
type f64 = float64
diff --git a/src/timeline.nim b/src/timeline.nim
index d7dfb159..eccee563 100644
--- a/src/timeline.nim
+++ b/src/timeline.nim
@@ -1,8 +1,8 @@
import std/[algorithm, options, os, sets, strformat, tables]
from std/math import round, ceil, exp, sin, PI
import ./[action, av, ffmpeg, log, media, wavutil]
-import ./lib/[cliputil, lang, transitions]
-import ./util/[color, fun, rational, speedmap]
+import ./lib/[cliputil, lang, paths, transitions]
+import ./util/[color, parse, rational, speedmap]
type v1* = object
chunks*: seq[(int64, int64, float64)]
diff --git a/src/util/abspath.nim b/src/util/abspath.nim
new file mode 100644
index 00000000..07afb49d
--- /dev/null
+++ b/src/util/abspath.nim
@@ -0,0 +1,11 @@
+import std/[os, strformat]
+import ../log
+import ../lib/paths
+
+proc absPath*(path: string): AbsPath {.raises: [AutoEditorError].} =
+ # absolutePath only fails if the cwd is gone or unreadable; nothing
+ # downstream can recover from that.
+ try:
+ AbsPath(path.absolutePath())
+ except CatchableError:
+ error &"Cannot resolve path: {path}"
diff --git a/src/util/bar.nim b/src/util/bar.nim
index 1ecd3b80..04ddea83 100644
--- a/src/util/bar.nim
+++ b/src/util/bar.nim
@@ -7,7 +7,7 @@ when defined(macosx):
import std/osproc
import ../log
-import ./term
+import ../lib/term
when not defined(windows):
var termResized {.global.}: Atomic[bool]
diff --git a/src/util/fun.nim b/src/util/fun.nim
deleted file mode 100644
index b1a1ee31..00000000
--- a/src/util/fun.nim
+++ /dev/null
@@ -1,397 +0,0 @@
-import std/[base64, os, strformat, strutils]
-from std/uri import decodeUrl
-from std/math import ceil, gcd, `mod`, round, trunc, pow
-import ../log
-import ../lib/[dnorm16, timeunit]
-import ./timecode
-
-func b64urlDecode*(s: string): seq[byte] =
- var padded = s.replace('-', '+').replace('_', '/')
- while padded.len mod 4 != 0:
- padded &= "="
- cast[seq[byte]](base64.decode(padded))
-
-func visibleLen(s: string): int =
- # Count only visible characters, skipping OSC escape sequences (\e]...\e\)
- var i = 0
- while i < s.len:
- if s[i] == '\e' and i + 1 < s.len and s[i + 1] == ']':
- i += 2
- while i < s.len:
- if s[i] == '\e' and i + 1 < s.len and s[i + 1] == '\\':
- i += 2
- break
- i += 1
- else:
- result += 1
- i += 1
-
-func wrapText*(text: string, width, indent: int): string =
- let text = text.strip(leading = true, trailing = true, chars = {'\n'})
- if text.len == 0:
- return ""
- let indentStr = " ".repeat(indent)
- var outLines: seq[string] = @[]
- var isFirst = true
-
- for line in text.split("\n"):
- if line.len == 0:
- outLines.add("")
- else:
- # Detect leading whitespace
- var leadingSpaces = 0
- for c in line:
- if c == ' ':
- leadingSpaces += 1
- else:
- break
- let lineIndent = " ".repeat(leadingSpaces)
- let content = line[leadingSpaces .. ^1]
-
- var currentLine = ""
- for word in content.splitWhitespace():
- if currentLine.len == 0:
- currentLine = word
- elif leadingSpaces + visibleLen(currentLine) + 1 + visibleLen(word) <= width:
- currentLine &= " " & word
- else:
- if isFirst:
- outLines.add(lineIndent & currentLine)
- isFirst = false
- else:
- outLines.add(indentStr & lineIndent & currentLine)
- currentLine = word
- if currentLine.len > 0:
- if isFirst:
- outLines.add(lineIndent & currentLine)
- isFirst = false
- else:
- outLines.add(indentStr & lineIndent & currentLine)
-
- result = outLines.join("\n")
-
-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}"
-
-when defined(posix):
- from std/posix import Stat, stat, S_ISREG, S_ISDIR, S_ISFIFO, S_ISSOCK
-
-proc isDevicePath*(path: string): bool {.raises: [].} =
- ## Whether `path` names something other than a file to create or replace:
- ## a device (/dev/null), a pipe (/dev/stdout, `>(cmd)`), or a socket. Its
- ## name is fixed, so nothing may add an extension or derive siblings from it.
- when defined(windows):
- let (_, name, _) = splitFile(path)
- path.startsWith(r"\\.\") or name.toUpperAscii in ["NUL", "CON", "PRN",
- "AUX", "COM1", "COM2", "COM3", "COM4", "LPT1", "LPT2", "LPT3"]
- elif defined(posix) and not defined(emscripten):
- # An alias of an open descriptor (/dev/stdout redirected to a file)
- # stats as whatever it points at.
- if path in ["/dev/stdout", "/dev/stderr"] or path.startsWith("/dev/fd/") or
- path.startsWith("/proc/") and "/fd/" in path:
- return true
- var st: Stat
- stat(path.cstring, st) == 0 and not S_ISREG(st.st_mode) and
- not S_ISDIR(st.st_mode)
- else:
- false
-
-proc isPipePath*(path: string): bool {.raises: [].} =
- ## Whether writing `path` can't seek back, as a muxer finishing its header
- ## would.
- when defined(posix) and not defined(emscripten):
- var st: Stat
- stat(path.cstring, st) == 0 and (S_ISFIFO(st.st_mode) or S_ISSOCK(st.st_mode))
- else:
- false
-
-func agSplitFile*(path: string): tuple[dir, name, ext: string] =
- ## Platform-independent splitFile. Treats both '/' and '\' as path separators
- ## on every OS, so results don't drift between Linux, macOS, and Windows.
- var namePos = 0
- var dotPos = 0
- for i in countdown(path.len - 1, 0):
- if path[i] == '.' and dotPos == 0:
- dotPos = i
- elif path[i] == '/' or path[i] == '\\':
- if namePos == 0:
- namePos = i + 1
- if dotPos > namePos and dotPos < path.len - 1:
- result.name = substr(path, namePos, dotPos - 1)
- result.ext = substr(path, dotPos)
- else:
- result.name = substr(path, namePos)
- result.dir = substr(path, 0, max(0, namePos - 2))
- return
- if dotPos > 0 and dotPos < path.len - 1:
- result.name = substr(path, 0, dotPos - 1)
- result.ext = substr(path, dotPos)
- else:
- result.name = path
-
-type AbsPath* = distinct string
- ## A filesystem path known to be absolute. `absPath` is the only
- ## constructor, so consumers can rely on the invariant (and stay `func`).
-
-proc absPath*(path: string): AbsPath {.raises: [AutoEditorError].} =
- # absolutePath only fails if the cwd is gone or unreadable; nothing
- # downstream can recover from that.
- try:
- AbsPath(path.absolutePath())
- except CatchableError:
- error &"Cannot resolve path: {path}"
-func `$`*(path: AbsPath): string {.borrow.}
-
-func pathToUri*(path: AbsPath): string {.raises: [].} =
- ## file:// URL for a path. Bytes outside the RFC 3986 path set (spaces,
- ## '#', '%', non-ASCII, ...) are percent-encoded.
- var p = $path
- when defined(windows):
- p = p.replace('\\', '/')
- result = "file:///"
- else:
- result = "file://"
- for c in p:
- if c in {'a'..'z', 'A'..'Z', '0'..'9', '-', '.', '_', '~', '/', ':'}:
- result.add c
- else:
- result.add '%'
- result.add toHex(ord(c), 2)
-
-func uriToPath*(uri: string): string {.raises: [].} =
- ## The path a file:// URL names, decoded; other strings unchanged.
- var path = uri
- if path.startsWith("file://localhost/"):
- # Windows-style: file://localhost/C:/... -> C:/...
- if path.len > 18 and path[18] == ':':
- path = path[17..^1]
- else:
- path = path[16..^1]
- elif path.startsWith("file://"):
- # Windows-style: file:///C:/... -> C:/...
- if path.len > 9 and path[9] == ':':
- path = path[8..^1]
- else:
- # Unix-style: file:///path -> /path
- path = path[7..^1]
- else:
- return uri
- return decodeUrl(path, decodePlus = false)
-
-const
- commonAspectRatios = [
- (1, 1), (5, 4), (4, 3), (3, 2), (16, 10), (16, 9), (2, 1), (64, 27)
- ]
- # Max drift, in stored pixels, between a dimension and what a common ratio
- # would produce for us to treat the difference as codec-friendly rounding
- # rather than a deliberate ratio. Absolute (not relative) so the snap stays
- # tight at high resolutions where a percentage would be many pixels wide.
- aspectSnapDrift = 2.0
-
-func aspectRatio*(width, height: int, sarNum = 1, sarDen = 1): tuple[w, h: int] =
- if width <= 0 or height <= 0:
- return (0, 0)
-
- # Fold the sample (pixel) aspect ratio into the dimensions so anamorphic video
- # reports its true display aspect ratio, the way ffmpeg's DAR does.
- let
- sn = max(sarNum, 1)
- sd = max(sarDen, 1)
- dispW = width * sn
- dispH = height * sd
- c = gcd(dispW, dispH)
- result = (dispW div c, dispH div c)
-
- # A clean, small reduction is already a meaningful ratio (16:9, 4:3, 8:5...).
- if max(result.w, result.h) <= 50:
- return
-
- let (w, h) = (width.float, height.float)
- var bestDrift = aspectSnapDrift
- for (cw, ch) in commonAspectRatios:
- for (a, b) in [(cw, ch), (ch, cw)]:
- # Stored dimensions that would yield this display ratio for the given SAR.
- let
- ta = float(a * sd) # storage-width units
- tb = float(b * sn) # storage-height units
- drift = max(abs(w - h * ta / tb), abs(h - w * tb / ta))
- if drift < bestDrift:
- bestDrift = drift
- result = (a, b)
-
-const
- minSampleRate* = 100
- maxSampleRate* = 768_000 ## the highest PCM rate in use
-
-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: float64
- try:
- floatNum = parseFloat(num.replace(" ", ""))
- except:
- error &"Invalid number: '{val}'"
- return (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
- # float -> int is unchecked: out of range or NaN, it's garbage. `not (a and
- # b)` so NaN fails too. A negative one would read as "auto".
- if not (bits >= 0 and bits < high(int).float64):
- error &"Bitrate out of range: {input}"
- int(bits)
-
-# 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 parseTimeSimple*(val: string): TimeSpec =
- let (num, unit) = splitNumStr(val)
- # float -> int is unchecked: out of range or NaN, it's garbage. `not (a and
- # b)` so NaN fails too.
- template checked(x: float64): int64 =
- let f = x
- if not (f > -timeSpan and f < timeSpan):
- 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"
- let x = (try: parseFloat(part) except ValueError: 0.0)
- 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)
diff --git a/src/util/parse.nim b/src/util/parse.nim
new file mode 100644
index 00000000..0ac645ec
--- /dev/null
+++ b/src/util/parse.nim
@@ -0,0 +1,145 @@
+## 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, 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])
+ try:
+ let floatNum = parseFloat(num.replace(" ", ""))
+ return (floatNum, unit)
+ except ValueError:
+ error &"Invalid number: '{val}'"
+
+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"
+ let x = (try: parseFloat(part) except ValueError: 0.0)
+ 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)
diff --git a/src/util/rules.nim b/src/util/rules.nim
index 13fdeebc..ff2130da 100644
--- a/src/util/rules.nim
+++ b/src/util/rules.nim
@@ -1,6 +1,6 @@
import std/strformat
import ../[ffmpeg, log]
-import ./fun
+import ../lib/paths
type Rules* = object
diff --git a/src/util/timecode.nim b/src/util/timecode.nim
index a3bab12a..9d806579 100644
--- a/src/util/timecode.nim
+++ b/src/util/timecode.nim
@@ -1,14 +1,41 @@
## SMPTE timecode, as EDLs count it: whole frames at an integer base, with
## drop-frame numbering for the NTSC rates.
+## Also `TimeSpec`, a time as written before the timeline's rate is known.
import std/strutils
from std/math import ceil
import ../ffmpeg
import ./rational
-type Timecode* = object
- h*, m*, s*, f*: int64
- drop*: bool ## written with a `;`, `.` or `,` separator
+type
+ TimeKind* = enum
+ tkFrames ## whole frames at the timeline's rate
+ tkMillis ## milliseconds
+ tkTimecode ## SMPTE timecode, counted at the timeline's rate
+ TimeSpec* = object
+ ## A time as written, made into frames once the timeline's rate is known.
+ case kind*: TimeKind
+ of tkFrames, tkMillis: n*: int64
+ of tkTimecode:
+ tc*: Timecode
+ neg*: bool
+ Timecode* = object
+ h*, m*, s*, f*: int64
+ drop*: bool ## written with a `;`, `.` or `,` separator
+
+func frames*(n: int64): TimeSpec {.raises: [].} =
+ TimeSpec(kind: tkFrames, n: n)
+
+func millis*(n: int64): TimeSpec {.raises: [].} =
+ TimeSpec(kind: tkMillis, n: n)
+
+func sign*(t: TimeSpec): int {.raises: [].} =
+ case t.kind
+ of tkFrames, tkMillis: cmp(t.n, 0'i64)
+ of tkTimecode:
+ if t.tc.h == 0 and t.tc.m == 0 and t.tc.s == 0 and t.tc.f == 0: 0
+ elif t.neg: -1
+ else: 1
func timecodeBase*(tb: AVRational): int64 {.inline.} =
## The frames a second holds in timecode: 30 for 29.97, 24 for 23.976.