Skip to content

Effort free video editing!

Take clock time and timecode in time ranges

WyattBluef3cc8455940c
diff --git a/docs/src/docs/range-syntax.md b/docs/src/docs/range-syntax.md
index 68e83859..7ee1b102 100644
--- a/docs/src/docs/range-syntax.md
+++ b/docs/src/docs/range-syntax.md
@@ -58,10 +58,29 @@ You can also use `s`, `sec`, `secs`, `second`, or `seconds`, depending on your p
To say frames outright, write `f`, `frame`, or `frames`: `--cut 0,30f` is the same as `--cut 0,30`.
+`min`, `minute`, `minutes`, `hour`, and `hours` work too.
+
+## Clock Time and Timecode
+A time can also be written with colons:
+
+ * `MM:SS` or `HH:MM:SS` is clock time, and the seconds may have a decimal: `1:30`, `1:02:03.5`.
+ * `HH:MM:SS:FF` is timecode, as an editor shows it. `FF` counts frames at the timeline's frame rate. Write `HH:MM:SS;FF` for drop-frame timecode on a 29.97 or 59.94 fps timeline.
+
+```sh
+# Cut from 1 minute 30 seconds to 2 minutes.
+auto-editor example.mp4 --cut 1:30,2:00
+
+# The same cut, as timecode on a 30 fps timeline.
+auto-editor example.mp4 --cut 00:01:30:00,00:02:00:00
+```
+
+Three fields always mean `HH:MM:SS`, never `MM:SS:FF`. For frames, write all four fields.
+
## Negative Indexes
Negative numbers can be used to count down starting from the end.
* `-60,end` selects the last 60 frames
* `1sec,-30secs` selects from the first second, to the last 30 seconds from the end.
+ * `-1:30,end` selects the last minute and a half.
## Speed for Range
The `--set-speed-for-range` option has a slight twist on time range syntax. It accepts three numbers. `speed`, `start`, and `end`, separated by commas. `speed` can be a decimal number, but not negative. `start` and `end` work as described above.
diff --git a/src/conductor.nim b/src/conductor.nim
index 1c44f4ed..f5bf67b7 100644
--- a/src/conductor.nim
+++ b/src/conductor.nim
@@ -126,8 +126,8 @@ proc parseExportString*(exportStr: string): ExportSpec {.raises: [AutoEditorErro
if i < paramsStr.len and paramsStr[i] == ',':
inc i
-func normalizeRange(span: (PackedInt, PackedInt), tb: float64,
- arrayLen: int): (int, int) {.raises: [].} =
+proc normalizeRange(span: (TimeSpec, TimeSpec), tb: float64,
+ arrayLen: int): (int, int) {.raises: [AutoEditorError].} =
var start = toTb(span[0], tb)
var stop = toTb(span[1], tb)
if start < 0:
@@ -136,7 +136,7 @@ func normalizeRange(span: (PackedInt, PackedInt), tb: float64,
stop = max(0, arrayLen + stop)
return (start, stop)
-proc applyToRange(actionIndex: var seq[int], span: (PackedInt, PackedInt), tb: float64,
+proc applyToRange(actionIndex: var seq[int], span: (TimeSpec, TimeSpec), tb: float64,
value: int, maxLen: int) {.raises: [AutoEditorError].} =
let len = if maxLen > 0: maxLen else: actionIndex.len
let (start, stop) = normalizeRange(span, tb, len)
@@ -165,7 +165,7 @@ proc appendIndices(actionMap: var seq[Actions], extra: Actions, sIdx: int,
actionMap.add made.getOrDefault((sIdx, k))
result[k] = actionMap.len - 1
-proc remapRange(actionIndex: var seq[int], span: (PackedInt, PackedInt), tb: float64,
+proc remapRange(actionIndex: var seq[int], span: (TimeSpec, TimeSpec), tb: float64,
remap: seq[int], maxLen: int) {.raises: [AutoEditorError].} =
let len = if maxLen > 0: maxLen else: actionIndex.len
let (start, stop) = normalizeRange(span, tb, len)
@@ -580,7 +580,7 @@ proc buildTimeline*(args: var mainArgs, audio: AudioSettings,
let lo = max(toTb(span[0], tbf) - concatOffset, 0)
let hi = min(toTb(span[1], tbf) - concatOffset, labels.len)
if hi > lo:
- remapRange(actionIndex, (pack(false, lo), pack(false, hi)), tbf, remap,
+ remapRange(actionIndex, (frames(lo), frames(hi)), tbf, remap,
getConLen())
else:
remapRange(actionIndex, span, tbf, remap, getConLen())
@@ -599,7 +599,7 @@ proc buildTimeline*(args: var mainArgs, audio: AudioSettings,
let lo = max(toTb(span[0], tbf) - concatOffset, 0)
let hi = min(toTb(span[1], tbf) - concatOffset, labels.len)
if hi > lo:
- applyToRange(actionIndex, (pack(false, lo), pack(false, hi)), tbf, aIdx,
+ applyToRange(actionIndex, (frames(lo), frames(hi)), tbf, aIdx,
getConLen())
else:
applyToRange(actionIndex, span, tbf, aIdx, getConLen())
@@ -626,7 +626,7 @@ proc buildTimeline*(args: var mainArgs, audio: AudioSettings,
applyAdds(tlV3, args, interner)
applyLayers(tlV3, args, interner)
tlV3.applyArgs(args, audio)
- if args.transition.getNumber > 0:
+ if args.transition.sign > 0:
tlV3.addTransitions(args.transitionKind,
toTb(args.transition, tlV3.tb.float).int64,
toTb(args.transitionMinCut, tlV3.tb.float).int64)
diff --git a/src/log.nim b/src/log.nim
index 2fc4081f..40154c94 100644
--- a/src/log.nim
+++ b/src/log.nim
@@ -5,6 +5,7 @@ when not defined(emscripten):
import ./[action, cli, editexpr, ffmpeg, transitions]
export editexpr, transitions
import ./util/[color, rational, term]
+import ./lib/timecode
type
AutoEditorError* = object of CatchableError
@@ -23,7 +24,17 @@ type
name*: string
version*: uint8
- PackedInt* = distinct int64
+ 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
@@ -42,20 +53,19 @@ func `$`*(kind: ExportKind): string {.raises: [].} =
of exPremiereOtio: "premiere-otio"
of exEdl: "edl"
-func pack*(flag: bool, number: int64): PackedInt {.raises: [].} =
- let maskedNumber = number and 0x7FFFFFFFFFFFFFFF'i64
- let flagBit = if flag: 0x8000000000000000'i64 else: 0'i64
- PackedInt(flagBit or maskedNumber)
+func frames*(n: int64): TimeSpec {.raises: [].} =
+ TimeSpec(kind: tkFrames, n: n)
-func getFlag*(packed: PackedInt): bool {.raises: [].} =
- int64(packed) < 0
+func millis*(n: int64): TimeSpec {.raises: [].} =
+ TimeSpec(kind: tkMillis, n: n)
-func getNumber*(packed: PackedInt): int64 {.raises: [].} =
- let raw = int64(packed) and 0x7FFFFFFFFFFFFFFF'i64
- if (raw and 0x4000000000000000'i64) != 0:
- raw or 0x8000000000000000'i64
- else:
- raw
+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
@@ -154,7 +164,7 @@ type
SourceMarker* = object
## A marker in the inputs' time, laid end to end, placed on the timeline
## through the cuts. `stop` equal to `start` makes it a point.
- start*, stop*: PackedInt
+ start*, stop*: TimeSpec
name*, note*: string
color*: MarkerColor
@@ -184,8 +194,8 @@ type mainArgs* = object
videoHookData*: pointer
# Editing Options
- margin*: (PackedInt, PackedInt) = (pack(true, 200), pack(true, 200)) # 0.2s
- smooth*: (PackedInt, PackedInt) = (pack(true, 200), pack(true, 100)) # 0.2s,0.1s
+ margin*: (TimeSpec, TimeSpec) = (millis(200), millis(200))
+ smooth*: (TimeSpec, TimeSpec) = (millis(200), millis(100))
edit*: EditExpr = edit(audioMethod())
whenInactive*: Actions = aCut
whenActive*: Actions = aNil
@@ -194,12 +204,12 @@ type mainArgs* = object
`export`*: ExportSpec = ExportSpec(
kind: exAuto, name: "Auto-Editor Media Group", version: 11)
output*: string = ""
- setAction*: seq[(Actions, PackedInt, PackedInt)]
+ setAction*: seq[(Actions, TimeSpec, TimeSpec)]
markers*: seq[SourceMarker] # in the inputs' frames end to end, like setActionConcat
adds*: seq[AddSpec] # `add:` overlays (see AddSpec)
layers*: seq[LayerSpec] # library-only overlays
- transition*: PackedInt = pack(false, 0) # 0 disables; otherwise its duration
- transitionMinCut*: PackedInt = pack(true, 1000) # 1 second
+ transition*: TimeSpec = frames(0) # 0 disables; otherwise its duration
+ transitionMinCut*: TimeSpec = millis(1000)
placedTransitions*: seq[PlacedTransition] # library-only: chosen in an editor
# URL download Options
diff --git a/src/main.nim b/src/main.nim
index 5ec7e5ca..9cc740ef 100644
--- a/src/main.nim
+++ b/src/main.nim
@@ -86,7 +86,7 @@ proc printHelp() {.noreturn.} =
echo ""
quit(0)
-proc parseTwoLengths(val, opt: string): (PackedInt, PackedInt) =
+proc parseTwoLengths(val, opt: string): (TimeSpec, TimeSpec) =
var vals = val.strip().split(",")
if vals.len == 1:
vals.add vals[0]
@@ -98,8 +98,8 @@ proc parseTwoLengths(val, opt: string): (PackedInt, PackedInt) =
error "Invalid number: 'start'"
return (parseTime(vals[0]), parseTime(vals[1]))
-proc parseTransition(val: string): (TransitionKind, PackedInt, PackedInt) =
- result[2] = pack(true, 1000) # default minimum cut: one second
+proc parseTransition(val: string): (TransitionKind, TimeSpec, TimeSpec) =
+ result[2] = millis(1000) # default minimum cut
let parts = val.split(':')
if parts.len notin [2, 3]:
error "--transition expects KIND:DURATION[:MIN-CUT]"
@@ -108,14 +108,14 @@ proc parseTransition(val: string): (TransitionKind, PackedInt, PackedInt) =
for info in transitionInfo: ids.add info.id
error &"Unknown transition kind: '{parts[0]}'{didYouMean(parts[0], ids)}"
result[1] = parseTimeSimple(parts[1])
- if result[1].getNumber <= 0:
+ if result[1].sign <= 0:
error "--transition duration must be greater than zero"
if parts.len == 3:
result[2] = parseTimeSimple(parts[2])
- if result[2].getNumber < 0:
+ if result[2].sign < 0:
error "--transition minimum cut duration cannot be negative"
-proc parseTimeRange(val, opt: string): (PackedInt, PackedInt) =
+proc parseTimeRange(val, opt: string): (TimeSpec, TimeSpec) =
var vals = val.strip().split(",")
if vals.len < 2:
error &"{opt} has too few arguments"
@@ -371,7 +371,7 @@ proc actionFromUserSpeed(val: float64): Actions =
elif val <= 0.0 or val >= 99999.0: aCut
else: newActions([Action(kind: actSpeed, val: val)])
-proc parseSpeedRange(val: string): (Actions, PackedInt, PackedInt) =
+proc parseSpeedRange(val: string): (Actions, TimeSpec, TimeSpec) =
let vals = val.strip().split(",")
if vals.len < 3:
error "--set-speed has too few arguments"
@@ -383,7 +383,7 @@ proc parseSpeedRange(val: string): (Actions, PackedInt, PackedInt) =
return (action, parseTime(vals[1]), parseTime(vals[2]))
proc parseActionAndRange(
- val: string, args: var mainArgs): (Actions, PackedInt, PackedInt) =
+ val: string, args: var mainArgs): (Actions, TimeSpec, TimeSpec) =
let parts = splitUnescaped(val.strip(), ',', textOnly = true)
if parts.len < 3:
error "--set-action has too few arguments"
diff --git a/src/util/fun.nim b/src/util/fun.nim
index 0d0242a6..9c71ea13 100644
--- a/src/util/fun.nim
+++ b/src/util/fun.nim
@@ -1,9 +1,9 @@
import std/[base64, os, strutils, strformat]
from std/uri import decodeUrl
-from std/math import gcd, `mod`, round, trunc, pow
+from std/math import ceil, gcd, `mod`, round, trunc, pow
import ../log
-import ../lib/[dnorm16, timeunit]
+import ../lib/[dnorm16, timecode, timeunit]
func b64urlDecode*(s: string): seq[byte] =
var padded = s.replace('-', '+').replace('_', '/')
@@ -301,44 +301,98 @@ proc parseBitrate*(input: string): int =
error &"Bitrate out of range: {input}"
int(bits)
-# A PackedInt holds 62 bits and a sign; "end" is the largest.
-const packedSpan = float64(1'i64 shl 62)
+# 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): PackedInt =
- const tb = 1000.0
+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 packed(flag: bool, x: float64): PackedInt =
+ template checked(x: float64): int64 =
let f = x
- if not (f > -packedSpan and f < packedSpan):
+ if not (f > -timeSpan and f < timeSpan):
error &"'{val}': Time is out of range"
- pack(flag, f.int64)
+ f.int64
var tu: TimeUnit
if not parseTimeUnit(unit, tu):
error &"'{val}': Time format got unknown unit: `{unit}`"
if tu != tuFrames:
- return packed(true, round(num * tb * tu.seconds))
+ 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 packed(false, num)
-
-proc parseTime*(val: string): PackedInt =
+ 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 pack(false, 0)
+ return frames(0)
if val == "end":
- return pack(false, 0x3FFFFFFFFFFFFFFF)
+ return frames(endFrames)
+ if ':' in val or ';' in val:
+ return parseClock(val)
return parseTimeSimple(val)
-func toTb*(val: PackedInt, tb: float64): int =
- if val.getFlag:
+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.getNumber.float64 / 1000.0 * tb)
+ 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))
- return f.int
- return int(val.getNumber)
+ 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)