Effort free video editing!
Answer with a sentinel where a raise was caught beside it
WyattBlue60316803494a
diff --git a/src/action.nim b/src/action.nimindex 0c05b13a..319d8c07 100644--- a/src/action.nim+++ b/src/action.nim@@ -1,5 +1,5 @@import std/[algorithm, hashes, math, options, sequtils, strformat, strutils]-import ./lib/[dnorm16, escape, suggest, timeunit]+import ./lib/[dnorm16, escape, numparse, suggest, timeunit]import ./util/colortype@@ -608,15 +608,16 @@ func applyEase*(e: Easing, t: float32): float32 =proc pFloat(s: string): float32 {.raises: [ActionParseError].} =# parseFloat accepts "nan" and "inf", which slip past `v < lo or v > hi`# checks and are UB when converted to an int.- result =- try: parseFloat(s).float32- except ValueError: raise newException(ActionParseError, &"Invalid float value: {s}")+ var f: float+ if not toFloat(s, f):+ raise newException(ActionParseError, &"Invalid float value: {s}")+ result = f.float32if classify(result) in {fcNan, fcInf, fcNegInf}:raise newException(ActionParseError, &"Invalid float value: {s}")proc pInt(s: string, what = "integer value"): int {.raises: [ActionParseError].} =- try: parseInt(s)- except ValueError: raise newException(ActionParseError, &"Invalid {what}: {s}")+ if not toInt(s, result):+ raise newException(ActionParseError, &"Invalid {what}: {s}")proc parseDuration(spec: string): (float32, DurUnit) {.raises: [ActionParseError].} =## "2s" or "2sec" -> (2, duSec); "30", "30f" or "30frames" -> (30, duFrames).@@ -625,9 +626,9 @@ proc parseDuration(spec: string): (float32, DurUnit) {.raises: [ActionParseErrorvar tu: TimeUnitif not parseTimeUnit(suffix, tu):raise newException(ActionParseError, &"Invalid duration: {spec}")- let n =- try: parseFloat(num)- except ValueError: raise newException(ActionParseError, &"Invalid duration: {spec}")+ var n: float+ if not toFloat(num, n):+ raise newException(ActionParseError, &"Invalid duration: {spec}")result =if tu == tuFrames: (n.float32, duFrames)else: (float32(n * tu.seconds), duSec)@@ -951,9 +952,8 @@ func flagV(on = true): Option[ArgValue] = some(ArgValue(kind: akFlag, on: on))proc pNum(s: string): float64 {.raises: [ActionParseError].} =## A number that's finite as the float32 it's packed into.- result =- try: parseFloat(s)- except ValueError: raise newException(ActionParseError, &"Invalid float value: {s}")+ if not toFloat(s, result):+ raise newException(ActionParseError, &"Invalid float value: {s}")if classify(float32(result)) in {fcNan, fcInf, fcNegInf}:raise newException(ActionParseError, &"Invalid float value: {s}")@@ -963,9 +963,9 @@ proc pDur(spec: string): (float64, DurUnit) {.raises: [ActionParseError].} =var tu: TimeUnitif not parseTimeUnit(suffix, tu):raise newException(ActionParseError, &"Invalid duration: {spec}")- let n =- try: parseFloat(num)- except ValueError: raise newException(ActionParseError, &"Invalid duration: {spec}")+ var n: float+ if not toFloat(num, n):+ raise newException(ActionParseError, &"Invalid duration: {spec}")result = if tu == tuFrames: (n, duFrames) else: (n * tu.seconds, duSec)# `not (a and b)` so NaN fails too; inf would write a timeline that can't# be read back.@@ -1097,9 +1097,7 @@ proc shapeSpec(parts: seq[string], name: string): ActionSpec {.else: -1proc setSlot(i: int, raw, ctx: string) {.raises: [ActionParseError].} =- try:- vals[i] = parseInt(raw)- except ValueError:+ if not toInt(raw, vals[i]):raise newException(ActionParseError, &"{name}: invalid integer: {ctx}")if vals[i] < low(int32).int or vals[i] > high(int32).int:raise newException(ActionParseError, &"{name}: value out of range: {ctx}")@@ -1148,9 +1146,9 @@ proc polySpec(parts: seq[string], name: string): ActionSpec {.var gotPoly = falseproc addPoint(raw, ctx: string): int32 {.raises: [ActionParseError].} =- let v = try: parseInt(raw)- except ValueError: raise newException(ActionParseError,- &"{name}: invalid integer: {ctx}")+ var v: int+ if not toInt(raw, v):+ raise newException(ActionParseError, &"{name}: invalid integer: {ctx}")if v < low(int32).int or v > high(int32).int:raise newException(ActionParseError, &"{name}: value out of range: {ctx}")int32(v)@@ -1175,8 +1173,9 @@ proc polySpec(parts: seq[string], name: string): ActionSpec {.for num in nums:pts.add addPoint(num, p)elif p.startsWith("feather="):- let v = try: parseInt(p[8 .. ^1])- except ValueError: raise newException(ActionParseError, &"{name}: invalid feather: {p}")+ var v: int+ if not toInt(p[8 .. ^1], v):+ raise newException(ActionParseError, &"{name}: invalid feather: {p}")if name == "mask": checkArg("mask", "feather", v)else: checkArg("confine", "feather", v)feather = vdiff --git a/src/cache.nim b/src/cache.nimindex 0202655f..ab1801ba 100644--- a/src/cache.nim+++ b/src/cache.nim@@ -53,29 +53,30 @@ proc saveCache[T](filename: string, data: seq[T]) =except OSError: discardraise-proc loadCache[T](filename: string): seq[T] =+proc loadCache[T](filename: string): Option[seq[T]] {.raises: [IOError].} =+ ## The levels in `filename`, or none when there is no such file or it+ ## doesn't hold a whole run of `T`.var f: Fileif not open(f, filename):- raise newException(IOError, "")+ returndefer: f.close()var header {.noinit.}: array[5, byte] # codec byte + int32 length- if f.readBuffer(addr header[0], 5) != 5:- raise newException(IOError, "cache truncated")- if header[0] != uint8(codecOf(T)):- raise newException(IOError, "cache codec mismatch")+ if f.readBuffer(addr header[0], 5) != 5 or header[0] != uint8(codecOf(T)):+ returnvar length32: int32copyMem(addr length32, addr header[1], 4)let length = length32.int# Untrusted length: newSeq on a corrupt value is an uncatchable RangeDefect# or a giant allocation.if length < 0 or length.int64 * sizeof(T) != f.getFileSize() - 5:- raise newException(IOError, "cache length corrupt")- result = newSeq[T](length)+ return+ var data = newSeq[T](length)if length > 0:let want = length * sizeof(T)- if f.readBuffer(addr result[0], want) != want:- raise newException(IOError, "cache truncated")+ if f.readBuffer(addr data[0], want) != want:+ return+ some(data)# Non-generic so `version` (referenced via the `&` macro) binds; it won't# inside a generic proc body.@@ -83,10 +84,11 @@ proc cacheDir(): string {.inline.} = getTempDir() / &"ae-{version}"proc cacheFilePath(path: AbsPath, tb: AVRational, kind, args: string): string =cacheDir() / &"{procTag(path, tb, kind, args)}.bin"-proc readCache*[T](path: string, tb: AVRational, kind, args: string): Option[seq[T]] =+proc readCache*[T](path: string, tb: AVRational, kind, args: string):+ Option[seq[T]] {.raises: [].} =try:- return some(loadCache[T](cacheFilePath(path.absPath, tb, kind, args)))- except Exception:+ return loadCache[T](cacheFilePath(path.absPath, tb, kind, args))+ except IOError, OSError, AutoEditorError:return none(seq[T])type CacheEntry = tuple[path: string, mtime: Time]diff --git a/src/cmds/levels.nim b/src/cmds/levels.nimindex 795e9b32..7220a89b 100644--- a/src/cmds/levels.nim+++ b/src/cmds/levels.nim@@ -1,32 +1,26 @@import std/[options, strformat, strutils]import ../[av, cache, cli, editparse, ffmpeg, log]import ../analyze/[audio, blackdetect, motion, subtitle]-import ../lib/[audioutil, dnorm16, tinyre]+import ../lib/[audioutil, dnorm16, numparse, tinyre]import ../util/rationalimport ./helpproc parseUnitFloat(name, value: string): float32 =- let f = (- try: parseFloat(value)- except ValueError: error &"Invalid {name}: {value}"- )+ var f: float+ if not toFloat(value, f): error &"Invalid {name}: {value}"# `not (>= and <=)` so NaN is rejected too.if not (f >= 0.0 and f <= 1.0): error &"{name} must be in range [0, 1]"result = f.float32proc parseStream(value: string): int16 =- let n = (- try: parseInt(value)- except ValueError: error &"Invalid stream: {value}"- )+ var n: int+ if not toInt(value, n): error &"Invalid stream: {value}"if n < 0 or n > 1000: error &"Invalid stream: {value}"result = n.int16proc parseNatural(name, value: string, positive = false): int32 =- let n = (- try: parseInt(value)- except ValueError: error &"Invalid {name}: {value}"- )+ var n: int+ if not toInt(value, n): error &"Invalid {name}: {value}"if (positive and n < 1) or n < 0 or n > high(int32):error &"Invalid {name}: {value}"result = n.int32diff --git a/src/cmds/whisper.nim b/src/cmds/whisper.nimindex b56c7d83..8ef427c5 100644--- a/src/cmds/whisper.nim+++ b/src/cmds/whisper.nim@@ -1,6 +1,6 @@import std/[os, strformat, strutils]import ../[av, cli, ffmpeg, log, transcribe]-import ../lib/dnorm16+import ../lib/[dnorm16, numparse]import ../util/parseimport ./helpwhen defined(macosx) or defined(windows) or@@ -50,18 +50,13 @@ proc main*(cArgs: seq[string]) =of coOutput:output = keyof coQueue:- queue = (- try: parseInt(key)- except ValueError: error &"Invalid --queue: {key}"- )+ if not toInt(key, queue): error &"Invalid --queue: {key}"queueExplicit = trueof coPrompt:prompt = keyof coThreads:- let n = (- try: parseInt(key)- except ValueError: error &"Invalid --threads: {key}"- )+ var n: int+ if not toInt(key, n): error &"Invalid --threads: {key}"if n < 1 or n > 1024:error &"--threads must be in range [1, 1024], got: {key}"threads = n.cintdiff --git a/src/edit.nim b/src/edit.nimindex fe13cf5d..3fc261e3 100644--- a/src/edit.nim+++ b/src/edit.nim@@ -1,7 +1,7 @@-import std/[math, options, os, sequtils, strformat, strutils]+import std/[math, options, os, sequtils, strformat]import ./[av, editexpr, editlexer, editparse, ffmpeg, log]import ./analyze/[audio, blackdetect, motion, subtitle]-import ./lib/[audioutil, dnorm16, suggest, tinyre, wordre]+import ./lib/[audioutil, dnorm16, numparse, suggest, tinyre, wordre]import ./util/[bar, parse, rational]type@@ -74,27 +74,26 @@ proc orWithThreshold(result: var seq[bool], levels: seq[Unorm16], t: Unorm16) =result.add levels[i] >= tproc parseFloatInRange(val: string, min, max: float32): float32 {.raises: [AutoEditorError].} =- try:- result = parseFloat(val)- except ValueError:+ var f: float+ if not toFloat(val, f):error &"Invalid number: {val}"+ result = f# `not (>= and <=)` instead of `< or >` so NaN is rejected too; it would# otherwise flow into unchecked float->int conversions downstream.if not (result >= min and result <= max):error &"value {result} is outside range [{min}, {max}]"proc parseNat(val: string): int32 =- let n = (- try: parseInt(val)- except ValueError: error &"Invalid natural: {val}"- )+ var n: int+ if not toInt(val, n): error &"Invalid natural: {val}"if n < 0 or n > high(int32).int: error &"Invalid natural: {val}"result = int32(n)proc parseStream(val: string): int16 =if val == "all":return -1- let n = (try: parseInt(val) except ValueError: error &"Invalid stream: {val}")+ var n: int+ if not toInt(val, n): error &"Invalid stream: {val}"if n > 1000 or n < 0: error &"Invalid stream: {val}"result = int16(n)diff --git a/src/imports/edl.nim b/src/imports/edl.nimindex 3216f3c7..b1925a27 100644--- a/src/imports/edl.nim+++ b/src/imports/edl.nim@@ -11,6 +11,7 @@import std/[algorithm, os, strformat, strutils, tables]from std/math import roundimport ../[action, av, ffmpeg, log, media, timeline]+import ../lib/numparseimport ../util/[color, rational, timecode]type@@ -206,15 +207,12 @@ proc parse(text: string): Parsed =if toks.len >= 3 and result.events.len > 0:var fpsAt = -1var tc: Timecode+ var fps: floatfor i in countdown(toks.len - 1, 2):- if not parseTimecode(toks[i], tc):- try:- discard parseFloat(toks[i])- fpsAt = i- break- except ValueError: discard+ if not parseTimecode(toks[i], tc) and toFloat(toks[i], fps):+ fpsAt = i+ breakif fpsAt >= 2:- let fps = (try: parseFloat(toks[fpsAt]) except ValueError: 0.0)result.events[^1].m2.add (toks[1 ..< fpsAt].join(" "), fps)elif upper.startsWith("AUD"):if result.events.len > 0 and result.events[^1].lines.len > 0:diff --git a/src/imports/fcp11.nim b/src/imports/fcp11.nimindex 01d6e43c..462230d7 100644--- a/src/imports/fcp11.nim+++ b/src/imports/fcp11.nim@@ -4,7 +4,7 @@import std/[algorithm, math, os, strformat, strutils, tables]import ../[action, av, log, timeline]-import ../lib/[audioutil, lang, paths]+import ../lib/[audioutil, lang, numparse, paths]import ../util/[color, rational, speedmap, xml]# Tags common in FCPXML, so the parsed tree can share their strings.@@ -56,15 +56,14 @@ proc seconds(s, what: string): float64 =if s.len < 2 or s[^1] != 's':error &"Invalid {what} time: '{s}'"let body = s[0 ..< ^1]- try:- let slash = body.find('/')- if slash < 0:- return parseBiggestInt(body).float64- let den = parseBiggestInt(body[slash + 1 .. ^1])- if den <= 0: error &"Invalid {what} time: '{s}'"- return parseBiggestInt(body[0 ..< slash]).float64 / den.float64- except ValueError:+ let slash = body.find('/')+ var num, den: BiggestInt = 1+ if slash < 0:+ if not toBiggestInt(body, num): error &"Invalid {what} time: '{s}'"+ elif not toBiggestInt(body[0 ..< slash], num) or+ not toBiggestInt(body[slash + 1 .. ^1], den) or den <= 0:error &"Invalid {what} time: '{s}'"+ num.float64 / den.float64proc attrSeconds(n: XmlNode, name: string, default = 0.0): float64 =let s = n.attr(name)@@ -102,11 +101,7 @@ proc clipEffects(r: var Reader, n: XmlNode, inSecs: float64, dur: int64,let amount = c.attr("amount")if amount.endsWith("dB"):var db: float64- try:- db = parseFloat(amount[0 ..< ^2])- except ValueError:- error &"Invalid adjust-volume amount: '{amount}'"- if db.isNaN:+ if not toFloat(amount[0 ..< ^2], db) or db.isNaN:error &"Invalid adjust-volume amount: '{amount}'"let gain = clamp(pow(10.0, db / 20.0), 0.0, 3.98109)if gain != 1.0:@@ -245,9 +240,7 @@ proc readConnected(r: var Reader, parent: XmlNode, parentStart: int64) =for c in parent:if c.kind == xnElement and c.attr("lane") != "":var lane: int- try:- lane = parseInt(c.attr("lane"))- except ValueError:+ if not toInt(c.attr("lane"), lane):error "Invalid lane: '" & c.attr("lane") & "'"if c.tag == "spine":r.dropped.inc "connected storyline"@@ -312,9 +305,7 @@ proc parseSampleRate(s: string): cint =## "48k", "44.1k", ...; 48000 when absent.if s == "": return 48000var rate: float64- try:- rate = parseFloat(s.strip(leading = false, chars = {'k'}))- except ValueError:+ if not toFloat(s.strip(leading = false, chars = {'k'}), rate):error &"Invalid audioRate: '{s}'"let hz = round(rate * (if s.endsWith('k'): 1000.0 else: 1.0))# `not (a and b)` so NaN fails too.@@ -345,21 +336,19 @@ proc fcp11ReadXml*(path: string, interner: var StringInterner): v3 =let fd = format.attr("frameDuration")let slash = fd.find('/')- let (fdNum, fdDen) =- try:- if fd.len > 1 and fd[^1] == 's' and slash > 0:- (parseInt(fd[0 ..< slash]), parseInt(fd[slash + 1 ..< ^1]))- else: (0, 0)- except ValueError: (0, 0)- if fdNum <= 0 or fdDen <= 0:+ var fdNum, fdDen: int+ if not (fd.len > 1 and fd[^1] == 's' and slash > 0 and+ toInt(fd[0 ..< slash], fdNum) and toInt(fd[slash + 1 ..< ^1], fdDen)) or+ fdNum <= 0 or fdDen <= 0:error &"Invalid frameDuration: '{fd}'"let g = gcd(fdNum, fdDen)if fdNum div g > high(cint) or fdDen div g > high(cint):error &"Invalid frameDuration: '{fd}'"r.tb = AVRational(num: cint(fdDen div g), den: cint(fdNum div g))- let w = (try: parseInt(format.attr("width")) except ValueError: 1920)- let h = (try: parseInt(format.attr("height")) except ValueError: 1080)+ var w, h: int+ if not toInt(format.attr("width"), w): w = 1920+ if not toInt(format.attr("height"), h): h = 1080if w < 1 or w > high(int32) or h < 1 or h > high(int32):error &"Invalid format size: {w}x{h}"diff --git a/src/imports/fcp7.nim b/src/imports/fcp7.nimindex 128f90fb..e8f95064 100644--- a/src/imports/fcp7.nim+++ b/src/imports/fcp7.nim@@ -1,7 +1,7 @@import std/[algorithm, sequtils, strformat, strutils, tables]from std/math import classify, fcInf, fcNan, fcNegInf, roundimport ../[action, ffmpeg, log, timeline]-import ../lib/[audioutil, paths]+import ../lib/[audioutil, numparse, paths]import ../util/[color, rational, speedmap, xml]# Tags common in FCP7 XML, so the parsed tree can share their strings.@@ -28,8 +28,7 @@ const maxFrames = 1'i64 shl 40proc xmlInt(node: XmlNode, lo = low(int64), hi = high(int64)): int64 =let s = node.innerText.strip()- result = try: parseBiggestInt(s)- except ValueError: error &"Invalid <{node.tag}> value: '{s}'"+ if not toBiggestInt(s, result): error &"Invalid <{node.tag}> value: '{s}'"if result < lo or result > hi:error &"Invalid <{node.tag}> value: '{s}'"@@ -48,10 +47,10 @@ func num(s: string): (bool, float) =case s.strip()of "TRUE": return (true, 1.0)of "FALSE": return (true, 0.0)- try:- let v = parseFloat(s.strip())- if v.classify in {fcNan, fcInf, fcNegInf}: (false, 0.0) else: (true, v)- except ValueError: (false, 0.0)+ var v: float+ if not toFloat(s.strip(), v) or v.classify in {fcNan, fcInf, fcNegInf}:+ (false, 0.0)+ else: (true, v)func readParam(parmNode: XmlNode): (string, seq[(float, float)]) =for c in parmNode:diff --git a/src/lib/numparse.nim b/src/lib/numparse.nimnew file mode 100644index 00000000..d0173b62--- /dev/null+++ b/src/lib/numparse.nim@@ -0,0 +1,27 @@+## Numbers read from a whole string, answering whether it was one rather+## than raising: what std/strutils' parseInt and parseFloat take, they take.+## A string that isn't a number leaves the result as it was.++import std/parseutils++func toBiggestInt*(s: string, n: var BiggestInt): bool =+ ## False for text that isn't an integer or is one too large to hold.+ var parsed: BiggestInt+ try:+ let used = parseBiggestInt(s, parsed)+ result = used > 0 and used == s.len+ except ValueError:+ result = false+ if result: n = parsed++func toInt*(s: string, n: var int): bool =+ var big: BiggestInt+ result = toBiggestInt(s, big) and big >= low(int) and big <= high(int)+ if result: n = int(big)++func toFloat*(s: string, f: var float): bool =+ ## "nan" and "inf" are floats here too.+ var parsed: float+ let used = parseFloat(s, parsed)+ result = used > 0 and used == s.len+ if result: f = parseddiff --git a/src/main.nim b/src/main.nimindex 1570b3eb..cdf32d01 100644--- a/src/main.nim+++ b/src/main.nim@@ -1,7 +1,7 @@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/[audioutil, escape, paths, suggest, term, text, tinyre]+import ./lib/[audioutil, escape, numparse, paths, suggest, term, text, tinyre]import ./render/burnsubsimport ./util/[color, parse, rational, timecode]from ./av import codecAlias@@ -410,8 +410,7 @@ proc parseLabeledFlag(key: string): tuple[matched: bool, kind: CliOption, label:else: return (false, coNone, 0)let suffix = key[ci + 1 .. ^1]var n: int- let parsedLen = (try: parseInt(suffix, n) except ValueError: 0)- if suffix.len == 0 or parsedLen != suffix.len:+ if not toInt(suffix, n):error &"Invalid label in {key}: expected an integer after ':'"if kind == coEdit and n == 0:error "--edit:0 is invalid (label 0 is reserved for silent; use --when:0 to act on silent sections)"diff --git a/src/render/h264.nim b/src/render/h264.nimindex 1cd8a89c..f9b1a8bc 100644--- a/src/render/h264.nim+++ b/src/render/h264.nim@@ -99,19 +99,16 @@ proc annexBToAvcC*(data: ptr uint8, size: int): seq[uint8] =result.add pif sps[0][1] notin [66'u8, 77, 88]:var r = rbspReader(sps[0], 4) # past the NAL header, profile and level- try:- discard r.ue # seq_parameter_set_id- let chroma = r.ue- if chroma == 3: discard r.bit- let lumaDepth = r.ue- let chromaDepth = r.ue- if chroma > 3 or lumaDepth > 7 or chromaDepth > 7:- return @[]- # no SPS extensions- result.add [0xfc'u8 or uint8(chroma), 0xf8'u8 or uint8(lumaDepth),- 0xf8'u8 or uint8(chromaDepth), 0x00]- except ValueError:+ discard r.ue # seq_parameter_set_id+ let chroma = r.ue+ if chroma == 3: discard r.bit+ let lumaDepth = r.ue+ let chromaDepth = r.ue+ if r.failed or chroma > 3 or lumaDepth > 7 or chromaDepth > 7:return @[]+ # no SPS extensions+ result.add [0xfc'u8 or uint8(chroma), 0xf8'u8 or uint8(lumaDepth),+ 0xf8'u8 or uint8(chromaDepth), 0x00]proc annexBParameterSets*(data: ptr uint8, size: int): seq[uint8] =## The SPS and PPS NAL units of an Annex B packet, still Annex B, ordiff --git a/src/render/hevc.nim b/src/render/hevc.nimindex 6429469c..6bebf239 100644--- a/src/render/hevc.nim+++ b/src/render/hevc.nim@@ -105,39 +105,36 @@ proc annexBToHvcC*(data: ptr uint8, size: int): seq[uint8] =var r = rbspReader(sps, 2)if r.data.len < 13:return- try:- discard r.bits(4) # sps_video_parameter_set_id- let maxSubLayers = r.bits(3)- let nesting = r.bit- let ptl = r.data[1 .. 12] # general profile, tier, flags and level- r.pos += 96- var profilePresent, levelPresent: array[8, bool]- for i in 0..<maxSubLayers:- profilePresent[i] = r.bit == 1- levelPresent[i] = r.bit == 1- if maxSubLayers > 0:- r.pos += 2 * (8 - maxSubLayers)- for i in 0..<maxSubLayers:- if profilePresent[i]: r.pos += 88- if levelPresent[i]: r.pos += 8- discard r.ue # sps_seq_parameter_set_id- let chroma = r.ue- if chroma == 3: discard r.bit- discard r.ue- discard r.ue- if r.bit == 1:- for _ in 0..3: discard r.ue- let lumaDepth = r.ue- let chromaDepth = r.ue- if chroma > 3 or lumaDepth > 7 or chromaDepth > 7:- return- result = @[1'u8]- result.add ptl- result.add [0xf0'u8, 0, 0xfc, 0xfc or uint8(chroma),- 0xf8 or uint8(lumaDepth), 0xf8 or uint8(chromaDepth), 0, 0,- uint8((maxSubLayers + 1) shl 3 or nesting shl 2 or 3), 3]- except ValueError:+ discard r.bits(4) # sps_video_parameter_set_id+ let maxSubLayers = r.bits(3)+ let nesting = r.bit+ let ptl = r.data[1 .. 12] # general profile, tier, flags and level+ r.pos += 96+ var profilePresent, levelPresent: array[8, bool]+ for i in 0..<maxSubLayers:+ profilePresent[i] = r.bit == 1+ levelPresent[i] = r.bit == 1+ if maxSubLayers > 0:+ r.pos += 2 * (8 - maxSubLayers)+ for i in 0..<maxSubLayers:+ if profilePresent[i]: r.pos += 88+ if levelPresent[i]: r.pos += 8+ discard r.ue # sps_seq_parameter_set_id+ let chroma = r.ue+ if chroma == 3: discard r.bit+ discard r.ue+ discard r.ue+ if r.bit == 1:+ for _ in 0..3: discard r.ue+ let lumaDepth = r.ue+ let chromaDepth = r.ue+ if r.failed or chroma > 3 or lumaDepth > 7 or chromaDepth > 7:return+ result = @[1'u8]+ result.add ptl+ result.add [0xf0'u8, 0, 0xfc, 0xfc or uint8(chroma),+ 0xf8 or uint8(lumaDepth), 0xf8 or uint8(chromaDepth), 0, 0,+ uint8((maxSubLayers + 1) shl 3 or nesting shl 2 or 3), 3]for i, list in nals:result.add [uint8(32 + i), uint8(list.len shr 8), uint8(list.len and 0xff)]for nal in list:diff --git a/src/render/smart.nim b/src/render/smart.nimindex 19c339a2..ab774073 100644--- a/src/render/smart.nim+++ b/src/render/smart.nim@@ -148,6 +148,7 @@ proc encodeFormat*(encoder: ptr AVCodec, format: AVPixelFormat): AVPixelFormat =type BitReader* = objectdata*: seq[uint8]pos*: int+ failed*: bool ## a read ran past the end or met a bad code; reads give 0func rbspReader*(nal: openArray[uint8], header: int): BitReader =## Reads a NAL unit's payload, past its `header` bytes, without the@@ -161,22 +162,25 @@ func rbspReader*(nal: openArray[uint8], header: int): BitReader =zeros = (if b == 0: zeros + 1 else: 0)result.data.add b-proc bit*(r: var BitReader): int =+func bit*(r: var BitReader): int =if r.pos >= r.data.len * 8:- raise newException(ValueError, "SPS ends early")+ r.failed = true+ return 0result = int((r.data[r.pos shr 3] shr (7 - (r.pos and 7))) and 1)inc r.pos-proc bits*(r: var BitReader, n: int): int =+func bits*(r: var BitReader, n: int): int =for _ in 0..<n:result = result shl 1 or r.bit-proc ue*(r: var BitReader): int =+func ue*(r: var BitReader): int =+ ## An Exp-Golomb code.var zeros = 0while r.bit == 0:inc zerosif zeros > 31:- raise newException(ValueError, "bad Exp-Golomb code")+ r.failed = true+ return 0(1 shl zeros) - 1 + r.bits(zeros)# --- Annex B <-> four-byte-length NAL conversion, shared by H.264 and HEVC ---diff --git a/src/util/color.nim b/src/util/color.nimindex 235d78ed..31f52f95 100644--- a/src/util/color.nim+++ b/src/util/color.nim@@ -54,7 +54,8 @@ func toRgb*(color: RGBColor, colorspace = 1, fullRange = false): RGBColor =func toByte(v: float): uint8 {.inline.} = uint8(round(clamp(v, 0.0, 1.0) * 255))RGBColor(red: toByte(r), green: toByte(g), blue: toByte(b))-func findColor(name: string): RGBColor {.raises: [ValueError].} =+func findColor(name: string, color: var RGBColor): bool =+ ## Sets `color` to the one FFmpeg knows as `name`; false if it knows none.var idx: cint = 0while true:var rgb: ptr uint8 = nil@@ -63,9 +64,10 @@ func findColor(name: string): RGBColor {.raises: [ValueError].} =breakif rgb != nil and cmpIgnoreCase($entry, name) == 0:let comps = cast[ptr UncheckedArray[uint8]](rgb)- return RGBColor(red: comps[0], green: comps[1], blue: comps[2])+ color = RGBColor(red: comps[0], green: comps[1], blue: comps[2])+ return trueinc idx- raise newException(ValueError, "Unknown color: " & name)+ falsefunc parseColor*(hexString: string): RGBColor {.raises: [ValueError].} =if hexString.toLowerAscii.startsWith("yuv#"):@@ -80,10 +82,9 @@ func parseColor*(hexString: string): RGBColor {.raises: [ValueError].} =returnif not hexString.startsWith("#"):- try:- return findColor(hexString)- except ValueError:+ if not findColor(hexString, result):raise newException(ValueError, "Unknown color name: " & hexString)+ returnlet hexValue = hexString.substr(1)if not hexValue.allCharsInSet(HexDigits):diff --git a/src/util/parse.nim b/src/util/parse.nimindex 0ac645ec..4bd4a70f 100644--- a/src/util/parse.nim+++ b/src/util/parse.nim@@ -2,7 +2,7 @@## units, thresholds, bitrates and times.import std/[math, strformat, strutils]-import ../lib/[dnorm16, timeunit]+import ../lib/[dnorm16, numparse, timeunit]import ../logimport ./timecode@@ -18,11 +18,10 @@ proc splitNumStr*(val: string): (float64, string) =breakindex += 1let (num, unit) = (val[0 ..< index], val[index .. ^1])- try:- let floatNum = parseFloat(num.replace(" ", ""))- return (floatNum, unit)- except ValueError:+ 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)@@ -105,7 +104,8 @@ proc parseClock(val: string): TimeSpec =elif c notin Digits: dots = 2if 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)+ 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 + xdiff --git a/src/util/xml.nim b/src/util/xml.nimindex a2176b27..6211c5fb 100644--- a/src/util/xml.nim+++ b/src/util/xml.nim@@ -206,16 +206,15 @@ proc writeXml*(root: XmlNode, output: string) {.raises: [AutoEditorError].} =const xmlMaxDepth = 256type- XmlTooDeep = object of CatchableError-XmlReader = objectx: XmlLexererrors: seq[string]tags: seq[string] # literals: a copy shares their storagetagIds: Table[string, int]+ tooDeep: bool # nesting passed xmlMaxDepth; every level stops readingproc parseElement(r: var XmlReader, depth: int): XmlNode- {.raises: [IOError, XmlTooDeep].}+ {.raises: [IOError].}template addError(r: var XmlReader, msg: string) =# Only the first error is reported, and `errorMsg` rereads the file up to@@ -231,10 +230,12 @@ proc addText(parent: XmlNode, text: string) =parent.children.add newText(text)proc parseChildren(r: var XmlReader, n: XmlNode, depth: int)- {.raises: [IOError, XmlTooDeep].} =+ {.raises: [IOError].} =if depth > xmlMaxDepth:- raise newException(XmlTooDeep, "")- while true:+ r.addError errorMsg(r.x, "elements nested deeper than " &+ $xmlMaxDepth & " levels")+ r.tooDeep = true+ while not r.tooDeep:case r.x.kindof xmlElementEnd:if r.x.elementName == n.str:@@ -264,7 +265,7 @@ proc parseChildren(r: var XmlReader, n: XmlNode, depth: int)r.x.next()proc parseElement(r: var XmlReader, depth: int): XmlNode- {.raises: [IOError, XmlTooDeep].} =+ {.raises: [IOError].} =let id = r.tagIds.getOrDefault(r.x.elementName, -1)result = newElement(if id >= 0: r.tags[id] else: r.x.elementName)if r.x.kind == xmlElementOpen:@@ -308,11 +309,7 @@ proc parseXmlFile*(path: string, knownTags: openArray[string] = []): XmlNoder.x.next()case r.x.kindof xmlElementOpen, xmlElementStart:- try:- result = r.parseElement(0)- except XmlTooDeep:- r.addError errorMsg(r.x, "elements nested deeper than " &- $xmlMaxDepth & " levels")+ result = r.parseElement(0)breakof xmlWhitespace, xmlSpecial, xmlPI: discardof xmlError: