Skip to content

Effort free video editing!

Improve style and remove `throttle.nim`

WyattBlue4e6a980cfd92
diff --git a/src/action.nim b/src/action.nim
index b5c357b7..53dafe57 100644
--- a/src/action.nim
+++ b/src/action.nim
@@ -30,20 +30,20 @@ type
coBottom, coTop, coCenter, coSides
BurnPart* = enum # what a burn's colors override; the order is part of atf-8
- bpColor, # the text
+ bpColor, # the text
bpOutline, # its outline
- bpBg # a box behind each subtitle
+ bpBg # a box behind each subtitle
DurUnit* = enum # how an ease duration is measured
- duClip, # the whole clip/section (the default)
- duSec, # seconds
- duFrames # timeline frames
+ duClip, # the whole clip/section (the default)
+ duSec, # seconds
+ duFrames # timeline frames
KfUnit* = enum # where a timed keyframe sits; the order is part of atf-8
- kuAuto, # between its timed neighbors (the first and last: the section's ends)
+ kuAuto, # between its timed neighbors (the first and last: the section's ends)
kuPercent, # percent of the section
- kuSec, # seconds from the section's start
- kuFrames # timeline frames from the section's start
+ kuSec, # seconds from the section's start
+ kuFrames # timeline frames from the section's start
KfTime* = object
at*: float32
unit*: KfUnit
@@ -55,7 +55,7 @@ type
# Easing envelope shared by every animatable action (zoom/blur/opacity/
# brightness/volume/pos). Defaults (off, linear, whole-clip) make a static
# action sample trivially, so non-animated actions just ignore these.
- easeDur*: float32 # magnitude in easeDurUnit (ignored for duClip)
+ easeDur*: float32 # magnitude in easeDurUnit (ignored for duClip)
hasEase*: bool
easeCurve*: Easing
easeDurUnit*: DurUnit
@@ -63,51 +63,51 @@ type
of actInvert, actHflip, actVflip, actLoop, actErosion:
discard
of actChoke:
- chokeN*: uint8 # matte-erosion passes (px to shrink the alpha matte)
+ chokeN*: uint8 # matte-erosion passes (px to shrink the alpha matte)
of actRotate:
- rStart*: Unorm16 # circular [0, 360) static angle (expands the canvas)
+ rStart*: Unorm16 # circular [0, 360) static angle (expands the canvas)
of actScale:
tScaleW*, tScaleH*: float32 # about the center
- tUniform*: bool # one value for both, as `scale:v` says
+ tUniform*: bool # one value for both, as `scale:v` says
of actTurn:
- tDeg*: float32 # clockwise about the center, without growing the frame
+ tDeg*: float32 # clockwise about the center, without growing the frame
of actBurn, actText:
- burnFile*: string # the subtitles: an .srt, .ass, or a file with a text stream
- burnFont*: string # a font file to draw them with; "" keeps their own
- burnSize*: float32 # text height, percent of the frame's; 0 keeps their own
+ burnFile*: string # the subtitles: an .srt, .ass, or a file with a text stream
+ burnFont*: string # a font file to draw them with; "" keeps their own
+ burnSize*: float32 # text height, percent of the frame's; 0 keeps their own
burnSet*: set[BurnPart] # which of burnColors replace the subtitles' own
burnColors*: array[BurnPart, uint32] # 0xRRGGBBAA
burnAlign*: uint8
burnVertical*: bool
burnAss*: bool
of actSpin:
- sStart*: Unorm16 # circular [0, 360) start angle
- sRate*: float32 # spin rate in degrees/second (continuous)
+ sStart*: Unorm16 # circular [0, 360) start angle
+ sRate*: float32 # spin rate in degrees/second (continuous)
of actLens:
k1*, k2*: Snorm16
of actSpeed:
- val*: float32 # the speed, or a ramp's mean speed over its media
+ val*: float32 # the speed, or a ramp's mean speed over its media
varispeed*: bool
- sKf*: seq[float32] # a ramp's keyframes across its media; empty if constant
- sKt*: seq[KfTime] # their times (auto or percent), or empty: evenly
+ sKf*: seq[float32] # a ramp's keyframes across its media; empty if constant
+ sKt*: seq[KfTime] # their times (auto or percent), or empty: evenly
of actZoom, actBlur, actOpacity, actBrightness, actVolume:
- kf*: seq[float32] # keyframes in native units; len >= 1
- kt*: seq[KfTime] # each keyframe's time, or empty: spread evenly
+ kf*: seq[float32] # keyframes in native units; len >= 1
+ kt*: seq[KfTime] # each keyframe's time, or empty: spread evenly
of actDeesser:
intensity*, maxd*, freq*: Unorm16
of actHighpass, actLowpass:
- cutoff*: uint16 # Hz
+ cutoff*: uint16 # Hz
of actDehum:
- humHz*: uint16 # the mains frequency
- humHarmonics*: uint8 # notches at humHz and its multiples, this many
+ humHz*: uint16 # the mains frequency
+ humHarmonics*: uint8 # notches at humHz and its multiples, this many
of actPitch:
# Semitones x 100. Cent buckets round-trip as exact decimal semitones
pCents*: int16
of actTone:
- note*: uint8 # MIDI note number; 69 = A4 = 440 Hz
- wave*: Waveform # timbre (sine unless given)
+ note*: uint8 # MIDI note number; 69 = A4 = 440 Hz
+ wave*: Waveform # timbre (sine unless given)
of actConvolve:
- irPath*: string # impulse response file, or a folder of H_LL/H_LR/H_RL/H_RR.wav
+ irPath*: string # impulse response file, or a folder of H_LL/H_LR/H_RL/H_RR.wav
of actDuck:
# Cross-track sidechain: rendered at the mix stage, not in the clip chain.
duckAmount*, duckThresh*: Unorm16 # 0..1; gain floor = 1 - amount
@@ -117,8 +117,8 @@ type
saturation*: float32
brighthue*: Snorm16
of actDrawbox:
- dbX*, dbY*, dbW*, dbH*: int32 # rectangle in pixels (x, y, width, height)
- dbColor*: RGBColor # outline color (RGB only)
+ dbX*, dbY*, dbW*, dbH*: int32 # rectangle in pixels (x, y, width, height)
+ dbColor*: RGBColor # outline color (RGB only)
of actPos:
# Overlay placement ramps: top-left x/y in canvas px and a size multiplier
# (1.0 = native). Each is a keyframe seq (len 1 = static) like the scalars.
@@ -129,14 +129,14 @@ type
similar*, blend*: Unorm16
of actAberration:
abRh*, abRv*, abGh*, abGv*, abBh*, abBv*: int8
- abWrap*: bool # edge: wrap around (true) vs smear the border (false)
+ abWrap*: bool # edge: wrap around (true) vs smear the border (false)
of actMask, actConfine, actMaskPoly, actConfinePoly:
# `mask` shapes the clip's alpha; `confine` restricts following effects to
# this region. Shared geometry, in canvas pixels like drawbox.
- mRadius*: int32 # corner radius px: 0=rect, >0=rounded rect, -1=ellipse
- mReset*: bool # confine bare: reset to full frame (region fields unused)
- mInvert*: bool # swap inside/outside
- mFeather*: uint8 # soft-edge width in px (0 = hard edge)
+ mRadius*: int32 # corner radius px: 0=rect, >0=rounded rect, -1=ellipse
+ mReset*: bool # confine bare: reset to full frame (region fields unused)
+ mInvert*: bool # swap inside/outside
+ mFeather*: uint8 # soft-edge width in px (0 = hard edge)
mX*, mY*, mW*, mH*: int32
mPolyXs*, mPolyYs*: seq[int32]
of actPixelate:
@@ -158,30 +158,30 @@ type
# atf-8: store actions in as small a space as possible, inspirited by utf-8.
ActionParseError* = object of CatchableError
- ActionFlag* = enum # capabilities of an action
+ ActionFlag* = enum # capabilities of an action
afAudio,
afVideo,
- afAnimatable # value can be a keyframe ramp (`a..b..c`) with easing
- afGenerator # may stand in for a file in `add:`, painting a clear canvas
+ afAnimatable # value can be a keyframe ramp (`a..b..c`) with easing
+ afGenerator # may stand in for a file in `add:`, painting a clear canvas
ActionFlags* = set[ActionFlag]
RangeDoc* = object
## An interval of allowed values.
lo*, hi*: float
- loIncl*, hiIncl*: bool # closed (inclusive) bounds
- each*: bool # the interval applies to each positional arg
+ loIncl*, hiIncl*: bool # closed (inclusive) bounds
+ each*: bool # the interval applies to each positional arg
ArgKind* = enum
## What an action argument is written as.
- akNumber, # a decimal number
- akInteger, # a whole number
- akColor, # a color name, #rgb, #rrggbb, #rrggbbaa, or yuv#YYUUVV where taken
- akChoice, # one of `choices`
- akPath, # a file or folder
- akText, # free text
+ akNumber, # a decimal number
+ akInteger, # a whole number
+ akColor, # a color name, #rgb, #rrggbb, #rrggbbaa, or yuv#YYUUVV where taken
+ akChoice, # one of `choices`
+ akPath, # a file or folder
+ akText, # free text
akKeyframes, # a number or a ramp `a..b..c`, each optionally `@time`
- akFlag, # present or not, written as its bare name
- akDuration, # a time: a frame count, or with a unit like `2sec`
- akPoints # x/y pairs, `x1/y1/x2/y2/...`
+ akFlag, # present or not, written as its bare name
+ akDuration, # a time: a frame count, or with a unit like `2sec`
+ akPoints # x/y pairs, `x1/y1/x2/y2/...`
ArgDef* = object
## One argument of an action. Positional arguments come in order;
## `keyword` ones are written `name=value`, anywhere after them.
@@ -189,7 +189,7 @@ type
kind*: ArgKind
range*: Option[RangeDoc] # every value, for keyframes; parseAction rejects others
optional*: bool
- default*: string # as written, when leaving it out means a value
+ default*: string # as written, when leaving it out means a value
keyword*: bool
choices*: seq[string]
unit*: string
@@ -873,19 +873,19 @@ type
of akNumber, akInteger: num*: float64
of akKeyframes:
kf*: seq[float64]
- kt*: seq[KfTime] # each keyframe's time, or empty when none has one
+ kt*: seq[KfTime] # each keyframe's time, or empty when none has one
of akColor, akChoice, akPath, akText:
- str*: string # as written, after it parses; text and paths unescaped
+ str*: string # as written, after it parses; text and paths unescaped
of akDuration:
- dur*: float64 # seconds for duSec, frames for duFrames
+ dur*: float64 # seconds for duSec, frames for duFrames
durUnit*: DurUnit
- of akFlag: on*: bool # confetti's `shimmer` is a `no-shimmer` that's off
+ of akFlag: on*: bool # confetti's `shimmer` is a `no-shimmer` that's off
of akPoints: pts*: seq[int32] # x1, y1, x2, y2, ...
SpecEase* = object
## An animated action's `:ease=curve[:duration]`.
curve*: Easing
- dur*: float64 # in `unit`; 0 for duClip
- unit*: DurUnit # duClip when no duration is written
+ dur*: float64 # in `unit`; 0 for duClip
+ unit*: DurUnit # duClip when no duration is written
ActionSpec* = object
## An action as written, before toAction packs it. `args` lines up with
## its ActionDef's, none where an argument isn't written. Numbers are
@@ -1067,10 +1067,10 @@ proc shapeSpec(parts: seq[string], name: string): ActionSpec {.
## Fields take positional or `key=value` form (freely mixed); `invert` is a
## bare flag. radius: 0 = rect, >0 = rounded-rect corner px, -1 = ellipse.
const slots = ["x", "y", "w", "h", "radius", "feather"] # positional order
- var vals: array[6, int] # x, y, w, h, radius, feather
+ var vals: array[6, int] # x, y, w, h, radius, feather
var seen: array[6, bool]
var inv = false
- var nextPos = 0 # next unfilled positional slot
+ var nextPos = 0 # next unfilled positional slot
func slotOf(key: string): int =
case key
@@ -2001,8 +2001,8 @@ when not defined(nimscript):
CodecMode = enum cmSize, cmWrite, cmRead
Codec[M: static CodecMode] = object
base: ptr UncheckedArray[uint8]
- head, pos: int # the action's header byte, and the next field
- tooMany, unpaired: bool # ramps that can't be packed, found when sizing
+ head, pos: int # the action's header byte, and the next field
+ tooMany, unpaired: bool # ramps that can't be packed, found when sizing
KfStore = enum ksF32, ksUnorm16, ksSnorm16, ksPixel
proc raw[M, T](c: var Codec[M], v: var T) =
@@ -2285,7 +2285,7 @@ when not defined(nimscript):
for a in list:
# Sizing only reads the action, so it goes by address, not a copy.
var c = Codec[cmSize](pos: 1)
- c.code((unsafeAddr a)[])
+ c.code((addr a)[])
# Keyframe counts are packed into one byte; a wrapped count would
# misalign every later field on decode.
if c.tooMany:
@@ -2303,7 +2303,7 @@ when not defined(nimscript):
for a in list:
base[i] = uint8(ord(a.kind))
var c = Codec[cmWrite](base: base, head: i, pos: i + 1)
- c.code((unsafeAddr a)[])
+ c.code((addr a)[])
i = c.pos
Actions(cast[int](p))
diff --git a/src/analyze/audio.nim b/src/analyze/audio.nim
index ef1c09dc..e0c63a43 100644
--- a/src/analyze/audio.nim
+++ b/src/analyze/audio.nim
@@ -113,7 +113,7 @@ proc newAudioIterator(sampleRate: cint, channelLayout: ptr AVChannelLayout,
# @ 48kHz read 1602 samples into a 1601-sample buffer).
result.maxBufferSize = int(ceil(result.exactSize))
let ret = av_samples_alloc(addr result.readBuffer, nil, result.channelCount,
- result.maxBufferSize.cint, result.targetFormat, 0)
+ result.maxBufferSize.cint, result.targetFormat, 0)
if ret < 0:
error "Could not allocate read buffer"
@@ -262,10 +262,7 @@ proc readChannelPeaks(iter: AudioIterator,
if v < minV: minV = v
if v > maxV: maxV = v
i += iter.channelCount
- result[outputIndex] = (
- float32(minV) / 32768.0'f32,
- float32(maxV) / 32768.0'f32,
- )
+ result[outputIndex] = (float32(minV) / 32768.0'f32, float32(maxV) / 32768.0'f32)
proc flushResampler(iter: AudioIterator) =
# Flush the resampler by passing nil frame
@@ -273,7 +270,7 @@ proc flushResampler(iter: AudioIterator) =
for flushedFrame in flushedFrames:
let ret = av_audio_fifo_write(iter.fifo, cast[pointer](addr flushedFrame.data[0]),
- flushedFrame.nb_samples)
+ flushedFrame.nb_samples)
if ret < flushedFrame.nb_samples:
error "Could not write flushed data to FIFO"
av_frame_free(addr flushedFrame)
diff --git a/src/analyze/motion.nim b/src/analyze/motion.nim
index b2e80797..068a5ed1 100644
--- a/src/analyze/motion.nim
+++ b/src/analyze/motion.nim
@@ -83,7 +83,8 @@ proc createFilterGraph(timeBase: AVRational, pixFmtName: string,
# Create buffer source with proper arguments
let bufferArgs = cstring(
- &"video_size={width}x{height}:pix_fmt={pixFmtName}:time_base={timeBase.num}/{timeBase.den}:pixel_aspect=1/1"
+ &"video_size={width}x{height}:pix_fmt={pixFmtName}:" &
+ &"time_base={timeBase.num}/{timeBase.den}:pixel_aspect=1/1"
)
var ret = avfilter_graph_create_filter(addr bufferSrc,
@@ -341,7 +342,7 @@ iterator motionness*(processor: var VideoProcessor, width, blur: int32,
prevIndex = index
proc motion*(bar: Bar, container: InputContainer, path: string, tb: AVRational,
- stream, width, blur: int32, rect: Unorm24x4): seq[Unorm16] =
+ stream, width, blur: int32, rect: Unorm24x4): seq[Unorm16] =
let cacheArgs = &"{stream},{width},{blur},{rect}"
if not noCache:
let cacheData = readCache[Unorm16](path, tb, "motion", cacheArgs)
diff --git a/src/av.nim b/src/av.nim
index bc9d70bb..ed8ac730 100644
--- a/src/av.nim
+++ b/src/av.nim
@@ -307,7 +307,7 @@ type InputContainer* = object
subtitle*: seq[ptr AVStream]
proc openFormatCtx*(file: cstring): ptr AVFormatContext {.raises: [IOError].} =
- var ret = avformat_open_input(addr result, file, nil, nil)
+ let ret = avformat_open_input(addr result, file, nil, nil)
if ret == AVERROR(ENOENT):
raise newException(IOError, &"Input file doesn't exist: {file}")
elif ret == AVERROR_INVALIDDATA:
@@ -383,7 +383,7 @@ proc scanVideoLength*(formatCtx: ptr AVFormatContext, video: ptr AVStream): AVRa
proc mediaLength*(container: InputContainer): AVRational =
# Result is in seconds.
- var formatCtx = container.formatContext
+ let formatCtx = container.formatContext
discard ffmpeg.av_seek_frame(formatCtx, -1, 0, AVSEEK_FLAG_BACKWARD)
if container.audio.len > 0:
@@ -482,7 +482,7 @@ iterator flushDecode*(container: InputContainer, index: cint,
## before sending more packets, so we never hit AVERROR(EAGAIN) on send, which would
## silently drop the packet.
var ret: cint
- var packet = container.packet
+ let packet = container.packet
var flushed = false
while true:
@@ -511,8 +511,8 @@ proc startPts*(container: InputContainer, stream: ptr AVStream): int64 =
container.formatContext.startPts(stream)
proc seek*(container: InputContainer, offset: int64, stream: ptr AVStream = nil) =
- var flags: cint = AVSEEK_FLAG_BACKWARD
- var streamIndex: cint = (if stream == nil: -1 else: stream.index)
+ let flags: cint = AVSEEK_FLAG_BACKWARD
+ let streamIndex: cint = (if stream == nil: -1 else: stream.index)
if av_seek_frame(container.formatContext, streamIndex, offset, flags) < 0:
error "Error seeking frame"
# Callers need to call `avcodec_flush_buffers()` after.
@@ -785,7 +785,7 @@ proc startEncoding*(self: var OutputContainer) =
let option = self.options.items[i]
discard av_dict_set(addr options, option.key.cstring, option.value.cstring, 0)
- var ret = avformat_write_header(outputCtx, addr options)
+ let ret = avformat_write_header(outputCtx, addr options)
if ret < 0:
error &"Write header: {av_err2str(ret)}"
@@ -873,7 +873,7 @@ iterator encode*(encoderCtx: ptr AVCodecContext, frame: ptr AVFrame,
packet: ptr AVPacket): ptr AVPacket =
let isFlush: bool = frame == nil
- var ret = avcodec_send_frame(encoderCtx, frame)
+ let ret = avcodec_send_frame(encoderCtx, frame)
if ret < 0:
error &"Error sending frame to encoder: {ret}"
diff --git a/src/cache.nim b/src/cache.nim
index 45081b5c..146fcf1e 100644
--- a/src/cache.nim
+++ b/src/cache.nim
@@ -38,7 +38,7 @@ proc saveCache[T](filename: string, data: seq[T]) =
fs.write(uint8(codecOf(T)))
fs.write(data.len.int32)
if data.len > 0:
- fs.writeData(unsafeAddr data[0], data.len * sizeof(T))
+ fs.writeData(addr data[0], data.len * sizeof(T))
fs.close()
# close ignores fclose's result, so the last buffered chunk can be lost
# to a full disk without an error; only the size shows it.
@@ -78,7 +78,7 @@ proc loadCache[T](filename: string): seq[T] =
# Non-generic so `version` (referenced via the `&` macro) binds; it won't
# inside a generic proc body.
-proc cacheDir(): string = getTempDir() / &"ae-{version}"
+proc cacheDir(): string {.inline.} = getTempDir() / &"ae-{version}"
proc cacheFilePath(path: AbsPath, tb: AVRational, kind, args: string): string =
cacheDir() / &"{procTag(path, tb, kind, args)}.bin"
diff --git a/src/cli.nim b/src/cli.nim
index c3245ebe..bc0cdb9f 100644
--- a/src/cli.nim
+++ b/src/cli.nim
@@ -32,7 +32,7 @@ const actionsRef = Link(href: "https://auto-editor.com/ref/actions",
type OptKind* = enum
Regular # expecting = $datum
- Flag # $datum = true
+ Flag # $datum = true
Special # args.`export` = parseExportString("$datum")
type CliOption* = enum
@@ -45,8 +45,8 @@ type CliOption* = enum
coOutputFormat, coYtDlpExtras, coProgress, coQuiet, coPreview, coVn, coAn, coSn,
coDn, coFaststart, coNoFaststart, coFragmented, coNoFragmented, coChapters,
coNoChapters, coVcodec, coVideoBitrate, coCrf, coGop, coVprofile, coPreset, coPixFmt,
- coScale, coFont, coNoSeek, coNoPartialLossless, coAcodec, coLayout, coAudioBitrate, coMixAudioStreams,
- coAudioNormalize, coOpen, coNoOpen, coKey, coShowVersion, coWebCodecs, coWhen
+ coScale, coFont, coNoSeek, coNoPartialLossless, coAcodec, coLayout, coAudioBitrate,
+ coMixAudioStreams, coAudioNormalize, coOpen, coNoOpen, coKey, coShowVersion, coWebCodecs, coWhen
type OptDef* = object
names*: string
diff --git a/src/cmds/desc.nim b/src/cmds/desc.nim
index 593ef2d2..1f27d5ba 100644
--- a/src/cmds/desc.nim
+++ b/src/cmds/desc.nim
@@ -18,7 +18,7 @@ proc main*(args: seq[string]) =
except IOError:
continue
- var entry = av_dict_get(formatContext.metadata, "description", nil, 0)
+ let entry = av_dict_get(formatContext.metadata, "description", nil, 0)
try:
if entry != nil:
stdout.write("\n" & $entry.value & "\n\n")
diff --git a/src/cmds/info.nim b/src/cmds/info.nim
index e532454c..2c99cdc0 100644
--- a/src/cmds/info.nim
+++ b/src/cmds/info.nim
@@ -233,7 +233,7 @@ proc printCodecList(ofmt: ptr AVOutputFormat, kind: CodecListKind) =
var videos, audios, subs, others: seq[string]
var seen: HashSet[AVCodecID]
- var bestVideo = ofmt.video_codec
+ let bestVideo = ofmt.video_codec
var bestAudio = ofmt.audio_codec
var bestSubtitle = ofmt.subtitle_codec
if kind in {clkCodecs, clkEncoders}:
diff --git a/src/cmds/levels.nim b/src/cmds/levels.nim
index 54a064c2..795e9b32 100644
--- a/src/cmds/levels.nim
+++ b/src/cmds/levels.nim
@@ -151,7 +151,7 @@ proc openLevels(inputFile: string, m: EditMethod, tb: AVRational): LevelsJob =
of ekMotion: &"{userStream},{m.width},{m.blur},{result.rect}"
else: ""
-proc close(job: var LevelsJob) = job.container.close()
+proc close(job: var LevelsJob) {.inline.} = job.container.close()
proc computeLevels(job: var LevelsJob): tuple[data: seq[Unorm16], decodeErrors: int] =
## Levels for audio, motion and blackdetect, via the analysis cache. The
diff --git a/src/cmds/subdump.nim b/src/cmds/subdump.nim
index ebd5400e..229c9d9a 100644
--- a/src/cmds/subdump.nim
+++ b/src/cmds/subdump.nim
@@ -54,7 +54,7 @@ type SubtitleCue* = tuple[start, stop: float64, text: string] ## seconds
proc readCues(path: string): seq[SubtitleCue] =
## The cues of the first subtitle stream in `path` that has any text; empty
## when it has none or can't be read.
- var container = (try: av.open(path) except IOError: return)
+ let container = (try: av.open(path) except IOError: return)
defer: container.close()
for i, st in container.subtitle:
# The previous stream left the demuxer at EOF. Some demuxers (srt) can't
diff --git a/src/cmds/whisper.nim b/src/cmds/whisper.nim
index d0b5cecd..77f41c9d 100644
--- a/src/cmds/whisper.nim
+++ b/src/cmds/whisper.nim
@@ -116,7 +116,7 @@ proc main*(cArgs: seq[string]) =
if isMic:
when defined(macosx) or defined(windows) or
(defined(linux) and not defined(emscripten)):
- var micInput = openMic()
+ let micInput = openMic()
fmtCtx = micInput.formatContext
audioStream = micInput.audioStream
# Capture buffers from here on, so speech during the (seconds-long) model
diff --git a/src/conductor.nim b/src/conductor.nim
index 544e6030..4d6d871c 100644
--- a/src/conductor.nim
+++ b/src/conductor.nim
@@ -73,7 +73,7 @@ proc parseExportString*(exportStr: string): ExportSpec {.raises: [AutoEditorErro
if i >= paramsStr.len:
break
- var paramStart = i
+ let paramStart = i
while i < paramsStr.len and paramsStr[i] notin {'=', ','}:
inc i
@@ -195,10 +195,10 @@ func exportExt(ext: string, myExport: ExportKind, hasVideo: bool): string =
else: ext
type OutputPlan* = object
- path*: string ## where to write
+ path*: string ## where to write
kind*: ExportKind
formatName*: string ## a name whose extension picks the container
- dropsVideo*: bool ## the named container can't hold the timeline's video
+ dropsVideo*: bool ## the named container can't hold the timeline's video
func planOutput*(userOut: string, `export`: ExportKind, path: string,
isUrl, hasVideo, device: bool): OutputPlan {.raises: [AutoEditorError].} =
@@ -258,7 +258,7 @@ func planOutput*(userOut: string, `export`: ExportKind, path: string,
result.formatName = result.path
type DeviceMux* = object
- fragment*: bool ## the container must be fragmented to be readable
+ fragment*: bool ## the container must be fragmented to be readable
warning*: string ## an option that had to be dropped, or ""
func deviceMux*(format: string, pipe, faststart, noFragmented: bool): DeviceMux
@@ -542,7 +542,7 @@ proc buildTimeline*(args: var mainArgs, audio: AudioSettings,
var appended: Table[(int, int), Actions]
for i in 0 ..< args.inputs.len:
- var container = (try: av.open(args.inputs[i]) except IOError as e: error e.msg)
+ let container = (try: av.open(args.inputs[i]) except IOError as e: error e.msg)
defer: container.close()
if i == 0 and args.frameRate == AVRational(num: 0, den: 0):
@@ -721,7 +721,7 @@ proc editMedia*(args: var mainArgs, inputVideo: VideoSettings, audio: AudioSetti
defer: interner.cleanup()
defer: freeActions(args, tlV3)
- if args.progress == BarType.machine and args.output != "-":
+ if args.progress == machine and args.output != "-":
conwrite "Starting"
let bar = initBar(args.progress)
@@ -916,7 +916,7 @@ proc editMedia*(args: var mainArgs, inputVideo: VideoSettings, audio: AudioSetti
bar.destroy()
let seconds = round(epochTime() - startTime, 2)
- notice &"Finished. took {seconds} seconds ({toTimecode(seconds, Code.display)})"
+ notice &"Finished. took {seconds} seconds ({toTimecode(seconds, display)})"
if args.noOpen or device:
discard
diff --git a/src/editexpr.nim b/src/editexpr.nim
index 17faf559..cf0df8f5 100644
--- a/src/editexpr.nim
+++ b/src/editexpr.nim
@@ -8,12 +8,12 @@ type
EditMethodKind* = enum
ekAudio, ekMotion, ekBlackdetect,
ekSubtitle ## a regex over subtitle lines (`subtitle`, `regex`)
- ekWord ## a whole word in subtitle lines
- ekNone ## every frame active
- ekAll ## no frame active
+ ekWord ## a whole word in subtitle lines
+ ekNone ## every frame active
+ ekAll ## no frame active
EditMethod* = object
- stream*: int ## -1 is every audio stream (audio only)
+ stream*: int ## -1 is every audio stream (audio only)
threshold*: Unorm16 ## audio, motion, blackdetect
case kind*: EditMethodKind
of ekAudio:
diff --git a/src/editlexer.nim b/src/editlexer.nim
index 69c8b7af..740a5fa7 100644
--- a/src/editlexer.nim
+++ b/src/editlexer.nim
@@ -49,7 +49,7 @@ func initLexer*(filename, text: string): Lexer =
result.pos = 0
result.`char` = (if text.len == 0: '\0' else: text[0])
-func sourceText*(self: Lexer): lent string =
+func sourceText*(self: Lexer): lent string {.inline.} =
self.text
func sourceText*(expr: Expr, text: string): string =
@@ -141,7 +141,7 @@ proc eat(self: var Parser) {.raises: [ValueError].} =
self.currentToken = self.nextToken
self.nextToken = self.lexer.getNextToken()
-func peek(self: Parser): Token =
+func peek(self: Parser): Token {.inline.} =
self.nextToken
func atomText*(expr: Expr, text: string): string {.raises: [ValueError].} =
diff --git a/src/editmethods.nim b/src/editmethods.nim
index 7f5f9151..02c644fb 100644
--- a/src/editmethods.nim
+++ b/src/editmethods.nim
@@ -10,13 +10,13 @@ type
emVideo, emAudio, emSubtitle
EditParam* = object
- name*: string ## positional argument name, e.g. "threshold"
- typ*: string ## doc type, e.g. "(U Natural 'all)"
+ name*: string ## positional argument name, e.g. "threshold"
+ typ*: string ## doc type, e.g. "(U Natural 'all)"
default*: string ## doc default; "" means the argument is required
EditMethodDef* = object
names*: seq[string] ## canonical name first, then aliases (share parsing)
- media*: EditMedia ## which stream the method analyzes
+ media*: EditMedia ## which stream the method analyzes
params*: seq[EditParam]
help*: string
diff --git a/src/exports/drops.nim b/src/exports/drops.nim
index 899a5c5b..6d3c8351 100644
--- a/src/exports/drops.nim
+++ b/src/exports/drops.nim
@@ -6,11 +6,11 @@ import ../[action, log, timeline]
type
LayerRule = enum
- lrAll # every layer is written
- lrBase # only the base layer
+ lrAll # every layer is written
+ lrBase # only the base layer
lrSameSource # the base, plus layers that only use the base's files: the
# editor reads those streams from the files it already has
- lrFirst # the first layer, when it only uses the base's files
+ lrFirst # the first layer, when it only uses the base's files
Support = object
actions: set[ActionKind]
diff --git a/src/exports/fcp7.nim b/src/exports/fcp7.nim
index bf339604..faa92bc0 100644
--- a/src/exports/fcp7.nim
+++ b/src/exports/fcp7.nim
@@ -260,7 +260,7 @@ proc makeFiledef(files: var FileDefs, clipitem: XmlNode, mi: MediaInfo,
proc dissolveItem(t: Transition, mediaType: string, timebase: int64,
ntsc: string): XmlNode
-func channelsOf(mi: MediaInfo, stream: int16): int =
+func channelsOf(mi: MediaInfo, stream: int16): int {.inline.} =
if stream >= 0 and stream.int < mi.a.len: max(1, mi.a[stream].channels.int) else: 1
type ResolveAudioIds = seq[seq[seq[int]]] # [layer][channel][clip] -> clipitem id; 0 if none
diff --git a/src/exports/json.nim b/src/exports/json.nim
index b1067750..b9dca426 100644
--- a/src/exports/json.nim
+++ b/src/exports/json.nim
@@ -63,7 +63,7 @@ func transitionsToJson(tracks: seq[seq[Transition]]): JsonNode {.raises: [].} =
result.add arr
func `%`(self: v1): JsonNode {.raises: [].} =
- var jsonChunks = self.chunks.mapIt(%[%it[0], %it[1], %it[2]])
+ let jsonChunks = self.chunks.mapIt(%[%it[0], %it[1], %it[2]])
return %* {
"version": "1",
"source": self.source,
diff --git a/src/exports/kdenlive.nim b/src/exports/kdenlive.nim
index d698deb0..4f29e1ae 100644
--- a/src/exports/kdenlive.nim
+++ b/src/exports/kdenlive.nim
@@ -26,11 +26,11 @@ type Kdenlive = object
tb: AVRational
globalOut: string # the timeline's length as a timecode
aChannels, vChannels: int
- uniquePaths: seq[string] # sources in order of first appearance
+ uniquePaths: seq[string] # sources in order of first appearance
sourceIds: Table[string, string] # path -> kdenlive:id
pathDuration: Table[string, float64]
chains, playlists, filterId, transitionId: int
- clipPlaylists: seq[XmlNode] # two sub-playlists per track
+ clipPlaylists: seq[XmlNode] # two sub-playlists per track
trackTractors: seq[XmlNode]
# (track, source path) -> chain id, per track type
audioChainOf, videoChainOf: Table[(int, string), int]
@@ -38,7 +38,7 @@ type Kdenlive = object
const zeroTc = "00:00:00.000"
-func nch(k: Kdenlive): int = k.aChannels + k.vChannels
+func nch(k: Kdenlive): int {.inline.} = k.aChannels + k.vChannels
func warpedProducerId(k: Kdenlive, w, channel: int): string =
## Producer ids for warped clips are a pure function of the clip's index in
@@ -46,7 +46,7 @@ func warpedProducerId(k: Kdenlive, w, channel: int): string =
## from entries cannot drift apart.
&"producer{1 + w * k.nch + channel}"
-proc tcf(k: Kdenlive, f: int64): string = toTimecode(f.float / k.tb.float, standard)
+proc tcf(k: Kdenlive, f: int64): string {.inline.} = toTimecode(f.float / k.tb.float, standard)
proc element(tag: string, attrs: openArray[(string, string)]): XmlNode =
result = newElement(tag)
@@ -224,8 +224,10 @@ proc addVideoEffects(k: var Kdenlive, parent: XmlNode, effects: Actions,
("av.t", $max(effect.dbW, effect.dbH)), ("av.replace", "0")])
of actPixelate:
k.addFilter(parent, "avfilter.pixelize", [
- ("av.width", mltAnimValue(effect, effect.pixWKf, effect.pixWKt, clipDur, fps, asInt = true)),
- ("av.height", mltAnimValue(effect, effect.pixHKf, effect.pixHKt, clipDur, fps, asInt = true)),
+ ("av.width",
+ mltAnimValue(effect, effect.pixWKf, effect.pixWKt, clipDur, fps, asInt = true)),
+ ("av.height",
+ mltAnimValue(effect, effect.pixHKf, effect.pixHKt, clipDur, fps, asInt = true)),
("av.mode", "avg"), ("av.planes", "7")], anim(effect, inTc, outTc))
of actAberration:
k.addFilter(parent, "avfilter.rgbashift", [
diff --git a/src/exports/otio.nim b/src/exports/otio.nim
index f94c6d08..9c7878ef 100644
--- a/src/exports/otio.nim
+++ b/src/exports/otio.nim
@@ -90,12 +90,10 @@ proc speedEffect(scalar: float): JsonNode =
"time_scalar": scalar
}
-proc opacityEffect(rate: float, pct: float): JsonNode =
+proc opacityEffect(rate: float, pct: float): JsonNode {.inline.} =
effectNode("AE.ADBE Opacity", "Opacity", "", true, jarr(
startParam("Opacity", 1, %pct, rate),
- startParam("Blend Mode", 2, %18, rate),
- startParam("Blend Mode", 3, %0, rate),
- ))
+ startParam("Blend Mode", 2, %18, rate), startParam("Blend Mode", 3, %0, rate)))
proc rotationParam(actions: Actions, srcStart, srcDur: float, clipDur: int,
rate: float): JsonNode =
@@ -258,41 +256,33 @@ proc opacityFor(actions: Actions, srcStart, srcDur: float, clipDur: int,
return effectNode("AE.ADBE Opacity", "Opacity", "", true, jarr(
%*{"DisplayName": "Opacity", "ID": 1,
"Keyframes": opacityKeyframes(a, srcStart, srcDur, clipDur, rate)},
- startParam("Blend Mode", 2, %18, rate),
- startParam("Blend Mode", 3, %0, rate),
- ))
+ startParam("Blend Mode", 2, %18, rate), startParam("Blend Mode", 3, %0, rate)))
opacityEffect(rate, 100.0)
-proc invertEffect(rate: float): JsonNode =
+proc invertEffect(rate: float): JsonNode {.inline.} =
effectNode("AE.ADBE Invert", "Invert", "", false, jarr(
- startParam("Channel", 1, %0, rate),
- startParam("Blend With Original", 2, %0.0, rate),
- ))
+ startParam("Channel", 1, %0, rate), startParam("Blend With Original", 2, %0.0, rate)))
-proc hflipEffect(): JsonNode =
+proc hflipEffect(): JsonNode {.inline.} =
effectNode("AE.ADBE Horizontal Flip", "Horizontal Flip", "", false, newJArray())
-proc vflipEffect(): JsonNode =
+proc vflipEffect(): JsonNode {.inline.} =
effectNode("AE.ADBE Vertical Flip", "Vertical Flip", "", false, newJArray())
-proc volumeEffect(): JsonNode =
+proc volumeEffect(): JsonNode {.inline.} =
effectNode("Internal Volume Stereo", "Volume", "", true, jarr(
- keyframeParam("Mute", 0),
- keyframeParam("Level", 1),
- ))
+ keyframeParam("Mute", 0), keyframeParam("Level", 1)))
-proc clipPanner(rate: float): JsonNode =
+proc clipPanner(rate: float): JsonNode {.inline.} =
effectNode("PanProcessor", "Panner", "Panner", false, jarr(
startParam("Balance", 0, %0.5, rate),
))
-proc audioFaderEffect(): JsonNode =
+proc audioFaderEffect(): JsonNode {.inline.} =
effectNode("AudioFader", "Track", "", false, jarr(
- keyframeParam("Volume", 0),
- keyframeParam("Mute", 1),
- ))
+ keyframeParam("Volume", 0), keyframeParam("Mute", 1)))
-proc trackPanner(): JsonNode =
+proc trackPanner(): JsonNode {.inline.} =
effectNode("PanProcessor", "Panner", "Panner", false, jarr(
keyframeParam("Balance", 0),
))
diff --git a/src/exports/shotcut.nim b/src/exports/shotcut.nim
index 9a6d313e..65d33f9b 100644
--- a/src/exports/shotcut.nim
+++ b/src/exports/shotcut.nim
@@ -78,8 +78,10 @@ proc addActionFilters(parent: XmlNode, effects: Actions, clipDur: int,
("av.t", $max(effect.dbW, effect.dbH)), ("av.replace", "0")])
of actPixelate:
parent.addFilter("avfilter.pixelize", [
- ("av.width", mltAnimValue(effect, effect.pixWKf, effect.pixWKt, clipDur, fps, asInt = true)),
- ("av.height", mltAnimValue(effect, effect.pixHKf, effect.pixHKt, clipDur, fps, asInt = true)),
+ ("av.width",
+ mltAnimValue(effect, effect.pixWKf, effect.pixWKt, clipDur, fps, asInt = true)),
+ ("av.height",
+ mltAnimValue(effect, effect.pixHKf, effect.pixHKt, clipDur, fps, asInt = true)),
("av.mode", "avg"), ("av.planes", "7")], "", anim(effect))
of actAberration:
parent.addFilter("avfilter.rgbashift", [
@@ -89,8 +91,8 @@ proc addActionFilters(parent: XmlNode, effects: Actions, clipDur: int,
("av.edge", if effect.abWrap: "wrap" else: "smear")])
else: discard
-func tc(f: int64, tb: AVRational): string =
- toTimecode(float(f / tb), Code.standard)
+func tc(f: int64, tb: AVRational): string {.inline.} =
+ toTimecode(float(f / tb), standard)
proc addFadeFilters(parent: XmlNode, tl: v3, clip: Clip,
fadeInDur, fadeOutDur: int64) =
@@ -195,8 +197,8 @@ proc shotcutWriteMlt*(output: string, tl: v3) =
playlistBin.addProp("xml_retain", "1")
mlt.add(playlistBin)
- let global_out = toTimecode(float(tl.len / tl.tb), Code.standard)
- let global_last = toTimecode(float((tl.len - 1) / tl.tb), Code.standard)
+ let global_out = toTimecode(float(tl.len / tl.tb), standard)
+ let global_last = toTimecode(float((tl.len - 1) / tl.tb), standard)
let producer = newElement("producer")
producer.attrs = {"id": "bg"}.toXmlAttributes()
@@ -243,9 +245,9 @@ proc shotcutWriteMlt*(output: string, tl: v3) =
# dissolves become fade filters on the clip itself.
type ClipPlan = object
entryIn, entryOut: int64 # source frames the plain entry still covers
- postroll: int64 # extra source frames the chain must expose
+ postroll: int64 # extra source frames the chain must expose
fadeInDur, fadeOutDur: int64
- outCenter: int # centered transition leaving this clip, or -1
+ outCenter: int # centered transition leaving this clip, or -1
var plans = newSeq[ClipPlan](layer.len)
for i, clip in layer:
diff --git a/src/ffmpeg.nim b/src/ffmpeg.nim
index 476aaa74..99c9fa71 100644
--- a/src/ffmpeg.nim
+++ b/src/ffmpeg.nim
@@ -452,7 +452,7 @@ func `$`*(layout: ptr AVChannelLayout): string =
else:
result = "unknown"
-template `$`*(layout: AVChannelLayout): string = $(unsafeAddr layout)
+template `$`*(layout: AVChannelLayout): string = $(addr layout)
func `$`*(layout: ref AVChannelLayout): string = $(addr layout[])
proc `=copy`*(dest: var AVChannelLayout, src: AVChannelLayout) {.error:
@@ -466,7 +466,7 @@ proc `=sink`*(dest: var AVChannelLayout, src: AVChannelLayout) =
# deep copy here would leak a custom-order layout's heap map (and its
# ENOMEM result would go unchecked). uninit frees dest's old map first.
av_channel_layout_uninit(addr dest)
- copyMem(addr dest, unsafeAddr src, sizeof(AVChannelLayout))
+ copyMem(addr dest, addr src, sizeof(AVChannelLayout))
type
# https://ffmpeg.org/doxygen/8.0/structAVFrame.html
diff --git a/src/imports/edl.nim b/src/imports/edl.nim
index da9d6d64..670776b6 100644
--- a/src/imports/edl.nim
+++ b/src/imports/edl.nim
@@ -310,10 +310,10 @@ type Importer = object
audioStreams: Table[ptr string, int] # probed audio stream counts
dropped: CountTable[string]
-func frames(im: Importer, tc: Timecode, drop: bool): int64 =
+func frames(im: Importer, tc: Timecode, drop: bool): int64 {.inline.} =
toFrames(tc, im.base, tc.drop or drop)
-func rec(im: Importer, tc: Timecode, drop: bool): int64 =
+func rec(im: Importer, tc: Timecode, drop: bool): int64 {.inline.} =
im.frames(tc, drop) - im.startFrames
proc speedOf(im: var Importer, ev: Event, reel: string): float64 =
@@ -327,7 +327,8 @@ proc speedOf(im: var Importer, ev: Event, reel: string): float64 =
return
let speed = abs(fps) / im.base.float64
if speed != speed or speed < 0.0001 or speed > 1000.0:
- warning &"EDL motion line for reel {reel} has an unusable speed ({fps}); the clip keeps normal speed"
+ warning &"EDL motion line for reel {reel} has an unusable speed ({fps}); " &
+ "the clip keeps normal speed"
return
if fps < 0: im.dropped.inc "reversed clip"
return speed
@@ -448,7 +449,7 @@ proc importEvent(im: var Importer, ev: Event) =
im.lay(line, t0, t1 - t0, im.frames(line.tcs[0], drop), speed,
im.effectsFor(speed))
-proc resolvePath(name, edlDir: string): string =
+proc resolvePath(name, edlDir: string): string {.inline.} =
if name.isAbsolute: name else: edlDir / name
proc resolveSources(p: var Parsed, edlDir: string, interner: var StringInterner) =
diff --git a/src/imports/fcp11.nim b/src/imports/fcp11.nim
index 6943bd13..26b3d224 100644
--- a/src/imports/fcp11.nim
+++ b/src/imports/fcp11.nim
@@ -70,7 +70,7 @@ proc attrSeconds(n: XmlNode, name: string, default = 0.0): float64 =
let s = n.attr(name)
if s == "": default else: seconds(s, name)
-func frames(r: Reader, secs: float64): int64 =
+func frames(r: Reader, secs: float64): int64 {.inline.} =
int64(round(secs * r.tb.num.float64 / r.tb.den.float64))
proc speedOf(r: var Reader, timeMap: XmlNode, inSecs: float64, dur: int64,
diff --git a/src/imports/json.nim b/src/imports/json.nim
index d6761347..6d677a5d 100644
--- a/src/imports/json.nim
+++ b/src/imports/json.nim
@@ -51,7 +51,7 @@ proc parseClip(node: JsonNode, interner: var StringInterner,
result.effects = index.intern(effects, group)
-func clampEase(v: float): float32 =
+func clampEase(v: float): float32 {.inline.} =
if v != v: defaultEase else: float32(clamp(v, 0.0, 100.0))
proc parseTransition(node: JsonNode): Transition {.raises: [AutoEditorError].} =
diff --git a/src/lib/transitions.nim b/src/lib/transitions.nim
index 9088b93b..b51c64f3 100644
--- a/src/lib/transitions.nim
+++ b/src/lib/transitions.nim
@@ -47,8 +47,8 @@ type
tkConstantPower, tkExponentialFade
TransitionInfo* = object
- id*: string # the name in v3 files and on the command line
- name*: string # Premiere's name
+ id*: string # the name in v3 files and on the command line
+ name*: string # Premiere's name
matchName*: string # Premiere's internal name, as its OTIO files carry it;
# empty for those Premiere no longer reads
diff --git a/src/lib/xmllexer.nim b/src/lib/xmllexer.nim
index e79cfb62..07827f2b 100644
--- a/src/lib/xmllexer.nim
+++ b/src/lib/xmllexer.nim
@@ -149,7 +149,7 @@ proc addRun(dest: var string, buf: string, first, last: int) {.inline.} =
if n > 0:
let old = dest.len
dest.setLen(old + n)
- copyMem(addr dest[old], unsafeAddr buf[first], n)
+ copyMem(addr dest[old], addr buf[first], n)
func skipNewline(L: XmlLexer, pos: int): int {.inline.} =
## Past the newline at `pos`, CR LF counting as one.
diff --git a/src/libass.nim b/src/libass.nim
index c30e1330..870a7c06 100644
--- a/src/libass.nim
+++ b/src/libass.nim
@@ -6,11 +6,11 @@ type
ASS_Track* {.importc, header: "<ass/ass.h>".} = object
PlayResX*, PlayResY*: cint
YCbCrMatrix*: cint
- Language*: cstring ## ISO 639-1; libass frees it with free()
+ Language*: cstring ## ISO 639-1; libass frees it with free()
ASS_Image* {.importc, header: "<ass/ass.h>".} = object
w*, h*, stride*: cint
bitmap*: ptr UncheckedArray[uint8] ## coverage, 255 for full
- color*: uint32 ## 0xRRGGBBAA, its alpha counting transparency
+ color*: uint32 ## 0xRRGGBBAA, its alpha counting transparency
dst_x*, dst_y*: cint
next*: ptr ASS_Image
ASS_MessageCallback* =
diff --git a/src/log.nim b/src/log.nim
index c2e1cb10..15830727 100644
--- a/src/log.nim
+++ b/src/log.nim
@@ -24,8 +24,8 @@ type
version*: uint8
TimeKind* = enum
- tkFrames ## whole frames at the timeline's rate
- tkMillis ## milliseconds
+ 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.
@@ -74,12 +74,12 @@ type
of nkNull:
discard
of nkEbu:
- i*: float32 # -70.0 to 5.0, default -24.0
- lra*: float32 # 1.0 to 50.0, default 7.0
- tp*: float32 # -9.0 to 0.0, default -2.0
+ i*: float32 # -70.0 to 5.0, default -24.0
+ lra*: float32 # 1.0 to 50.0, default 7.0
+ tp*: float32 # -9.0 to 0.0, default -2.0
gain*: float32 # -99.0 to 99.0, default 0.0
of nkPeak:
- t*: float32 # -99.0 to 0.0, default -8.0
+ t*: float32 # -99.0 to 0.0, default -8.0
func `==`*(a, b: Norm): bool {.raises: [].} =
if a.kind != b.kind: return false
@@ -205,8 +205,8 @@ type mainArgs* = object
output*: string = ""
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
+ adds*: seq[AddSpec] # `add:` overlays (see AddSpec)
+ layers*: seq[LayerSpec] # library-only overlays
transition*: TimeSpec = frames(0) # 0 disables; otherwise its duration
transitionMinCut*: TimeSpec = millis(1000)
placedTransitions*: seq[PlacedTransition] # library-only: chosen in an editor
diff --git a/src/main.nim b/src/main.nim
index 62f4d817..5930289a 100644
--- a/src/main.nim
+++ b/src/main.nim
@@ -118,7 +118,7 @@ proc parseTransition(val: string): (TransitionKind, TimeSpec, TimeSpec) =
error "--transition minimum cut duration cannot be negative"
proc parseTimeRange(val, opt: string): (TimeSpec, TimeSpec) =
- var vals = val.strip().split(",")
+ let vals = val.strip().split(",")
if vals.len < 2:
error &"{opt} has too few arguments"
if vals.len > 2:
diff --git a/src/media.nim b/src/media.nim
index 7d55f5a4..88b4c087 100644
--- a/src/media.nim
+++ b/src/media.nim
@@ -188,11 +188,11 @@ func recommendedTimebase*(mi: MediaInfo): AVRational {.raises: [].} =
if mi.v.len > 0: makeSaneTimebase(mi.v[0].avg_rate)
else: AVRational(num: 30, den: 1)
-proc codecName*(id: AVCodecID): string = $avcodec_get_name(id)
+proc codecName*(id: AVCodecID): string {.inline.} = $avcodec_get_name(id)
proc mediaFrames*(path: string, tb: AVRational): int =
## How many frames auto-editor gives `path` on a timeline at `tb`: the
## audio's last packet, else the video's duration.
- var container = (try: av.open(path) except IOError as e: error e.msg)
+ let container = (try: av.open(path) except IOError as e: error e.msg)
defer: container.close()
int(round((mediaLength(container) * tb).float64))
diff --git a/src/mic.nim b/src/mic.nim
index 08a35ef1..3942a247 100644
--- a/src/mic.nim
+++ b/src/mic.nim
@@ -222,7 +222,7 @@ proc initGapFiller*(stream: ptr AVStream): GapFiller =
bytesPerFrame = (bits div 8) * par.ch_layout.nb_channels
initGapFiller(stream.time_base, par.sample_rate, bytesPerFrame)
-proc hasPending*(g: GapFiller): bool = g.pending != nil
+proc hasPending*(g: GapFiller): bool {.inline.} = g.pending != nil
proc feed*(g: var GapFiller, src: ptr AVPacket) =
## Take ownership of the next captured packet; `emit` hands it back, after
diff --git a/src/render/audio.nim b/src/render/audio.nim
index f0884558..6e080e2c 100644
--- a/src/render/audio.nim
+++ b/src/render/audio.nim
@@ -112,8 +112,8 @@ func clamp16(v: int32): int16 {.inline.} =
int16(max(-32768'i32, min(32767'i32, v)))
const
- toneTableLen = 2048 # one cycle; lerp error at this size is below -110 dBFS
- tonePeak = 8191.0 # -12 dBFS, so four stacked layers sum without clipping
+ toneTableLen = 2048 # one cycle; lerp error at this size is below -110 dBFS
+ tonePeak = 8191.0 # -12 dBFS, so four stacked layers sum without clipping
proc toInt16(frame: ptr AVFrame, srcStart, count: int, dst: var seq[int16],
dstStart, dstChannels: int): bool =
@@ -411,7 +411,7 @@ proc createFilterGraph(effects: openArray[Action], sr: cint,
let bufferArgs = &"sample_rate={sr}:sample_fmt=s16p:channel_layout={layout}:time_base=1/{sr}"
var bufferSrc: ptr AVFilterContext = nil
var ret = avfilter_graph_create_filter(addr bufferSrc, abuffer, nil,
- bufferArgs.cstring, nil, filterGraph)
+ bufferArgs.cstring, nil, filterGraph)
if ret < 0:
error &"Cannot create audio buffer source: {ret}"
@@ -421,9 +421,9 @@ proc createFilterGraph(effects: openArray[Action], sr: cint,
error &"Cannot create audio buffer sink: {ret}"
var filters: seq[string] = @[]
- var rate = 1.0 # asetrate
- var tempo = 1.0 # atempo
- var at = -1 # track asetrate/atempo's position
+ var rate = 1.0 # asetrate
+ var tempo = 1.0 # atempo
+ var at = -1 # track asetrate/atempo's position
for effect in effects:
case effect.kind
of actSpeed:
@@ -442,7 +442,7 @@ proc createFilterGraph(effects: openArray[Action], sr: cint,
var speedFx: seq[string] = @[]
if rate != 1.0:
speedFx.add &"asetrate={sr}*{rate}"
- speedFx.add &"aresample={sr}" # asetrate leaves the rate changed
+ speedFx.add &"aresample={sr}" # asetrate leaves the rate changed
speedFx.add atempoChain(tempo)
if speedFx.len > 0:
let i = max(at, 0)
@@ -1352,7 +1352,8 @@ proc makeAudioFrames*(fmt: AVSampleFormat, tl: v3, frameSize: int, layerIndices:
of nkEbu:
let layoutDesc = $tl.layout
- let bufferArgs = &"sample_rate={sr}:sample_fmt=fltp:channel_layout={layoutDesc}:time_base=1/{sr}"
+ let bufferArgs = &"sample_rate={sr}:sample_fmt=fltp:channel_layout={layoutDesc}:" &
+ &"time_base=1/{sr}"
# First pass: stream chunks through loudnorm to measure loudness.
let capture = beginLoudnormCapture()
@@ -1393,14 +1394,17 @@ proc makeAudioFrames*(fmt: AVSampleFormat, tl: v3, frameSize: int, layerIndices:
measuredLRA = parseLoudnormValue(jsonData, "input_lra")
measuredTP = parseLoudnormValue(jsonData, "input_tp")
measuredThresh = parseLoudnormValue(jsonData, "input_thresh")
- debug &"Measured: i={measuredI:.2f} lra={measuredLRA:.2f} tp={measuredTP:.2f} thresh={measuredThresh:.2f}"
+ debug &"Measured: i={measuredI:.2f} lra={measuredLRA:.2f} " &
+ &"tp={measuredTP:.2f} thresh={measuredThresh:.2f}"
except JsonParsingError, KeyError, ValueError:
error "Error processing loudnorm output"
else:
error "Error processing loudnorm output"
# Second pass: stream chunks through loudnorm applying the measured gain.
- let secondPass = &"i={norm.i}:lra={norm.lra}:tp={norm.tp}:offset={norm.gain}:linear=true:measured_i={measuredI}:measured_lra={measuredLRA}:measured_tp={measuredTP}:measured_thresh={measuredThresh}:print_format=none"
+ let secondPass = &"i={norm.i}:lra={norm.lra}:tp={norm.tp}:offset={norm.gain}:linear=true:" &
+ &"measured_i={measuredI}:measured_lra={measuredLRA}:measured_tp={measuredTP}:" &
+ &"measured_thresh={measuredThresh}:print_format=none"
debug &"EBU norm: {secondPass}"
var loudnormGraph = newGraph()
let bufferSrc = loudnormGraph.add("abuffer", bufferArgs)
diff --git a/src/render/convolve.nim b/src/render/convolve.nim
index 0716fd8f..c6dfbfaa 100644
--- a/src/render/convolve.nim
+++ b/src/render/convolve.nim
@@ -8,7 +8,7 @@ type
taps: seq[seq[seq[float32]]]
Spectra = ref object # shared with the cache, which every clip reads
- n: int # FFT size
+ n: int # FFT size
blockLen: int # input samples per FFT, so a block plus the IR tail fits in n
h: seq[seq[seq[AVComplexFloat]]]
@@ -117,7 +117,7 @@ proc loadIR(path: string, sr: cint, channels: int): IRMatrix =
if channels == 2: stereo else: fold(stereo, channels)
proc newTx(inv: bool, n: int, scale: float32): (ptr AVTXContext, av_tx_fn) =
- var s = scale
+ let s = scale
if av_tx_init(addr result[0], addr result[1], AV_TX_FLOAT_RDFT, cint(inv),
n.cint, addr s, AV_TX_UNALIGNED) < 0:
error "Could not set up the FFT"
diff --git a/src/render/format.nim b/src/render/format.nim
index 20fa621c..1898a9d9 100644
--- a/src/render/format.nim
+++ b/src/render/format.nim
@@ -1,6 +1,6 @@
import std/[algorithm, heapqueue, options, sequtils, sets, strformat, strutils]
from std/math import round
-import ../[action, av, ffmpeg, license, log, media, throttle, timeline]
+import ../[action, av, ffmpeg, license, log, media, timeline]
import ../util/[bar, rational, rules]
import ./[asyncenc, audio, partialplan, subtitle, video]
@@ -139,7 +139,6 @@ proc makeMedia*(args: mainArgs, inputVideo: VideoSettings, audio: AudioSettings,
defer:
for i in sourceEffectCount ..< renderTl.effects.len:
renderTl.effects[i].free()
- var throttle = initThrottle()
let includeVideo = not args.vn and rules.defaultVid notin [ID_NONE, ID_PNG]
let includeAudio = not args.an and rules.defaultAud != ID_NONE
let includeSubtitle = not args.sn and rules.defaultSub != ID_NONE
@@ -579,7 +578,6 @@ proc makeMedia*(args: mainArgs, inputVideo: VideoSettings, audio: AudioSettings,
(outputStream == vOutStream or vOutStream == nil):
let time = float(packet.pts) * float(packet.time_base)
bar.tick(round(time * tl.tb))
- throttle.checkpoint(time)
output.mux(packet[])
var ownedPacket = packet
av_packet_free(addr ownedPacket)
@@ -604,7 +602,6 @@ proc makeMedia*(args: mainArgs, inputVideo: VideoSettings, audio: AudioSettings,
let time = frame.time(encCtx.time_base)
if time != -1.0:
bar.tick(round(time * tl.tb))
- throttle.checkpoint(time)
output.mux(outPacket[])
av_packet_unref(outPacket)
diff --git a/src/render/h264.nim b/src/render/h264.nim
index 43672615..6d5b34e2 100644
--- a/src/render/h264.nim
+++ b/src/render/h264.nim
@@ -126,7 +126,7 @@ proc h264SupportsPartialLossless*(format: cint, header: seq[uint8]): bool =
## it has none (MPEG-TS).
if format != AV_PIX_FMT_YUV420P.cint or header.len == 0:
return false
- let extra = unsafeAddr header[0]
+ let extra = addr header[0]
# Annex B sources get their samples and an avcC rewritten as they copy.
if isAnnexB(extra, header.len):
return annexBToAvcC(extra, header.len).len > 0
diff --git a/src/render/hevc.nim b/src/render/hevc.nim
index d1bcd6d5..812cdd07 100644
--- a/src/render/hevc.nim
+++ b/src/render/hevc.nim
@@ -216,7 +216,7 @@ proc hevcSupportsPartialLossless*(format: cint, encoder: ptr AVCodec,
## it has none (MPEG-TS).
if not encoder.encoderSupports(AVPixelFormat(format)) or header.len == 0:
return false
- let extra = unsafeAddr header[0]
+ let extra = addr header[0]
# Annex B sources get their samples and an hvcC rewritten as they copy.
if startCodeLen(cast[ptr UncheckedArray[uint8]](extra), header.len, 0) > 0:
return annexBToHvcC(extra, header.len).len > 0
diff --git a/src/render/partialplan.nim b/src/render/partialplan.nim
index 65587d31..57c1add9 100644
--- a/src/render/partialplan.nim
+++ b/src/render/partialplan.nim
@@ -232,7 +232,9 @@ proc partialLosslessPlan*(output: OutputContainer, tl: v3, args: mainArgs,
let averageGop = averageGopFrames(keyframes, sourceEnd)
if not smartPlanIsWorthwhile(stats, tl.len, sourceEnd, averageGop):
let label = codecId.codecLabel
- debug &"Skipping {label} partial-lossless rendering: copying {stats.copiedFrames}/{tl.len} frames across {plan.len} spans would not offset {stats.encodeRuns} encoder runs"
+ debug &"Skipping {label} partial-lossless rendering: copying " &
+ &"{stats.copiedFrames}/{tl.len} frames across {plan.len} spans " &
+ &"would not offset {stats.encodeRuns} encoder runs"
return
return plan
@@ -289,7 +291,7 @@ proc makePartialLossless*(output: var OutputContainer, tl: v3, video: VideoSetti
bytes
let sourceParameterSets =
if header.len == 0: newSeq[uint8]()
- else: parameterSetsFor(codecId, unsafeAddr header[0], header.len)
+ else: parameterSetsFor(codecId, addr header[0], header.len)
let stats = smartPlanStats(spans)
if stats.copiedFrames == 0:
@@ -297,19 +299,19 @@ proc makePartialLossless*(output: var OutputContainer, tl: v3, video: VideoSetti
error &"Partial-lossless {label} renderer selected without a complete GOP"
let outputStream = output.addStreamFromTemplate(sourceStream)
- let sourceAnnexB = header.len > 0 and isAnnexB(unsafeAddr header[0], header.len)
+ let sourceAnnexB = header.len > 0 and isAnnexB(addr header[0], header.len)
if sourceAnnexB and isNal:
# The muxer reads Annex B extradata as Annex B samples, but every sample
# here is length-prefixed, so it gets an avcC or hvcC instead.
let record =
- if codecId == ID_H264: annexBToAvcC(unsafeAddr header[0], header.len)
- else: annexBToHvcC(unsafeAddr header[0], header.len)
+ if codecId == ID_H264: annexBToAvcC(addr header[0], header.len)
+ else: annexBToHvcC(addr header[0], header.len)
let par = outputStream.codecpar
av_freep(addr par.extradata)
par.extradata = cast[ptr uint8](av_mallocz(csize_t(record.len + 64)))
if par.extradata == nil:
error &"Could not allocate {label} header"
- copyMem(par.extradata, unsafeAddr record[0], record.len)
+ copyMem(par.extradata, addr record[0], record.len)
par.extradata_size = record.len.cint
if sourceStream.metadata != nil:
discard av_dict_copy(addr outputStream.metadata, sourceStream.metadata, 0)
@@ -331,7 +333,9 @@ proc makePartialLossless*(output: var OutputContainer, tl: v3, video: VideoSetti
let sourceDelay = max(sourceStream.codecpar.video_delay, 0).int64
templateInput.close()
- debug &"Using {label} partial-lossless rendering: copying {stats.copiedFrames}/{tl.len} frames across {spans.len} spans and {stats.encodeRuns} encoder runs"
+ debug &"Using {label} partial-lossless rendering: copying " &
+ &"{stats.copiedFrames}/{tl.len} frames across {spans.len} spans " &
+ &"and {stats.encodeRuns} encoder runs"
return (outputStream, iterator(): (ptr AVPacket, int64) =
let frameTb = av_inv_q(tl.tb)
diff --git a/src/render/preview.nim b/src/render/preview.nim
index 5fe34f67..5665da4d 100644
--- a/src/render/preview.nim
+++ b/src/render/preview.nim
@@ -32,7 +32,7 @@ proc openPreview*(args: sink mainArgs, startSeconds, scale: float64,
## `scale` of the timeline's frame size. Audio comes stereo at the
## timeline's rate, without normalization (which measures the whole
## timeline first). Owns `args` (its actions are freed on `close`).
- var r = PreviewRender(args: args)
+ let r = PreviewRender(args: args)
# ffv1 never encodes; it only settles the pixel format.
let video = VideoSettings(codec: "ffv1", scale: scale)
let built = buildTimeline(r.args, AudioSettings(layout: "stereo"), r.interner,
diff --git a/src/render/smart.nim b/src/render/smart.nim
index fb732e83..edd702c9 100644
--- a/src/render/smart.nim
+++ b/src/render/smart.nim
@@ -187,10 +187,10 @@ proc normalizeLengthPrefixed*(packet: ptr AVPacket,
if av_new_packet(packet, total.cint) < 0:
error "Could not allocate normalized " & label & " packet"
if parameterSets.len > 0:
- copyMem(packet.data, unsafeAddr parameterSets[0], parameterSets.len)
+ copyMem(packet.data, addr parameterSets[0], parameterSets.len)
if payload.len > 0:
copyMem(cast[pointer](cast[int](packet.data) + parameterSets.len),
- unsafeAddr payload[0], payload.len)
+ addr payload[0], payload.len)
packet.pts = pts
packet.dts = dts
packet.duration = duration
diff --git a/src/render/subtitle.nim b/src/render/subtitle.nim
index 9e362535..0242236f 100644
--- a/src/render/subtitle.nim
+++ b/src/render/subtitle.nim
@@ -161,7 +161,7 @@ proc writeCaptions*(track: CaptionTrack, ctx: ptr AVCodecContext,
var rect: AVSubtitleRect
rect.`type` = SUBTITLE_ASS
rect.ass = line.cstring
- var rectPtr = addr rect
+ let rectPtr = addr rect
var sub: AVSubtitle
sub.format = 1 # text
sub.end_display_time = uint32(dur) # ctx.time_base is milliseconds
diff --git a/src/render/transition.nim b/src/render/transition.nim
index f90df863..c8c02386 100644
--- a/src/render/transition.nim
+++ b/src/render/transition.nim
@@ -106,13 +106,13 @@ func fbm(x, y: float32, seed: uint32): float32 =
amp *= 0.5
result /= 0.9375
-func newImg(w, h: int): Img = Img(w: w, h: h, px: newSeq[uint8](w * h * 3))
+func newImg(w, h: int): Img {.inline.} = Img(w: w, h: h, px: newSeq[uint8](w * h * 3))
func newImgUninit(w, h: int): Img =
## For a picture whose every pixel is about to be written.
Img(w: w, h: h, px: newSeqUninit[uint8](w * h * 3))
template pixels(im: Img): ptr UncheckedArray[uint8] =
- cast[ptr UncheckedArray[uint8]](im.px[0].unsafeAddr)
+ cast[ptr UncheckedArray[uint8]](im.px[0].addr)
func get(im: Img, x, y: int): C {.inline.} =
let x = max(0, min(x, im.w - 1))
@@ -239,8 +239,8 @@ proc mixImg(a, b: Img, t: float32): Img =
if t == 0 or a.px.len == 0: return a
if t == 1: return b
result = Img(w: a.w, h: a.h, px: newSeqUninit[uint8](a.px.len))
- let pa = cast[ptr UncheckedArray[uint8]](a.px[0].unsafeAddr)
- let pb = cast[ptr UncheckedArray[uint8]](b.px[0].unsafeAddr)
+ let pa = cast[ptr UncheckedArray[uint8]](a.px[0].addr)
+ let pb = cast[ptr UncheckedArray[uint8]](b.px[0].addr)
let pd = cast[ptr UncheckedArray[uint8]](result.px[0].addr)
let rowBytes = a.w * 3
# Byte by byte, as `mix` and `put` do per channel, in a flat loop the
@@ -279,7 +279,7 @@ proc boxBlur(im: Img, rx, ry: int): Img =
return im
let (w, h) = (im.w, im.h)
var across: Img
- var src = unsafeAddr im
+ var src = addr im
if rx > 0:
across = blurAcross(src, rx, 0, w - 1)
src = addr across
@@ -358,7 +358,7 @@ proc grow(im: Img, w, h: int): Img =
let ih = im.h
eachRows(h, proc (y0, y1: int) {.closure, gcsafe.} =
let (sp, dp, sw, w, ih) = (sp, dp, sw, w, ih)
- let cp = cast[ptr UncheckedArray[tuple[a, b, wa, wb: int]]](cols[0].unsafeAddr)
+ let cp = cast[ptr UncheckedArray[tuple[a, b, wa, wb: int]]](cols[0].addr)
for y in y0 ..< y1:
let t = growTaps(ih, y)
let (ra, rb, o) = (t.a * sw, t.b * sw, y * w * 3)
@@ -702,7 +702,7 @@ proc render*(kind: TransitionKind, a, b, under: Img, p: float32, frame,
let row = min(rows - 1, int(y.float32 / bh))
let delay = float32(col + row) / float32(cols + rows - 2) * 0.5'f32
let t = easeInOut(clamp01((p - delay) / 0.5'f32))
- let src = (if t < 0.5: a.unsafeAddr else: b.unsafeAddr)
+ let src = (if t < 0.5: a.addr else: b.addr)
let s = (if t < 0.5: 1 - 2 * t else: 2 * t - 1)
let ccx = (col.float32 + 0.5'f32) * bw
let ccy = (row.float32 + 0.5'f32) * bh
@@ -718,7 +718,7 @@ proc render*(kind: TransitionKind, a, b, under: Img, p: float32, frame,
let vertical = kind == tk3dSpinback
let shrink = (if kind == tkFlipMotion: 0'f32 else: 0.25'f32 * bell(p))
let first = angle < PI / 2
- let src = (if first: a.unsafeAddr else: b.unsafeAddr)
+ let src = (if first: a.addr else: b.addr)
let ang = (if first: angle else: angle - PI.float32)
result.eachPixel(w, h):
let sx = (x.float32 + 0.5'f32 - fw / 2) / (1 - shrink) + fw / 2
@@ -745,7 +745,7 @@ proc render*(kind: TransitionKind, a, b, under: Img, p: float32, frame,
of tkPopMotion:
let first = p < 0.5'f32
let s = (if first: 1 - easeInBack(2 * p) else: easeOutBack(2 * p - 1))
- let src = (if first: a.unsafeAddr else: b.unsafeAddr)
+ let src = (if first: a.addr else: b.addr)
result.eachPixel(w, h):
c = (if s > 1e-3: under.placeOver(src[], x, y, s, s, 0, 0, 0)
else: under.get(x, y))
@@ -755,7 +755,7 @@ proc render*(kind: TransitionKind, a, b, under: Img, p: float32, frame,
let q = (if first: easeIn(2 * p) else: 1 - easeOut(2 * p - 1))
let grow = (if kind == tkPullMotion: 1.5'f32 else: 0.6'f32)
let s = 1 + q * grow
- let src = (if first: a.unsafeAddr else: b.unsafeAddr)
+ let src = (if first: a.addr else: b.addr)
var scaled: Img
scaled.eachPixel(w, h):
c = src[].sample((x.float32 + 0.5'f32 - fw / 2) / s + fw / 2,
@@ -770,7 +770,7 @@ proc render*(kind: TransitionKind, a, b, under: Img, p: float32, frame,
let first = p < 0.5'f32
let q = (if first: easeIn(2 * p) else: 1 - easeOut(2 * p - 1))
let angle = (if first: q else: -q) * PI.float32
- let src = (if first: a.unsafeAddr else: b.unsafeAddr)
+ let src = (if first: a.addr else: b.addr)
var turnedImg: Img
turnedImg.eachPixel(w, h):
c = under.placeOver(src[], x, y, 1 + 0.4'f32 * q, 1 + 0.4'f32 * q, angle, 0, 0)
@@ -817,8 +817,8 @@ proc render*(kind: TransitionKind, a, b, under: Img, p: float32, frame,
hi[ord(fromB)] = max(hi[ord(fromB)], c1)
# Together the two pictures show one frame's width, so blur only the
# columns each is read at.
- if rx > 0 and lo[0] <= hi[0]: amOwn = blurAcross(a.unsafeAddr, rx, lo[0], hi[0])
- if rx > 0 and lo[1] <= hi[1]: bmOwn = blurAcross(b.unsafeAddr, rx, lo[1], hi[1])
+ if rx > 0 and lo[0] <= hi[0]: amOwn = blurAcross(a.addr, rx, lo[0], hi[0])
+ if rx > 0 and lo[1] <= hi[1]: bmOwn = blurAcross(b.addr, rx, lo[1], hi[1])
let pa = (if amOwn.px.len > 0: amOwn.pixels else: a.pixels)
let pb = (if bmOwn.px.len > 0: bmOwn.pixels else: b.pixels)
type Tap = tuple[src: ptr UncheckedArray[uint8], o0, o1: int, tx: float32]
@@ -831,7 +831,7 @@ proc render*(kind: TransitionKind, a, b, under: Img, p: float32, frame,
# Straight from the bytes, with `mix` and `put`'s steps in their order.
eachRows(h, proc (y0, y1: int) {.closure, gcsafe.} =
let (dp, w) = (dp, w)
- let tp = cast[ptr UncheckedArray[Tap]](taps[0].unsafeAddr)
+ let tp = cast[ptr UncheckedArray[Tap]](taps[0].addr)
for y in y0 ..< y1:
let row = y * w * 3
for x in 0 ..< w:
@@ -846,8 +846,8 @@ proc render*(kind: TransitionKind, a, b, under: Img, p: float32, frame,
if rx > 0:
amOwn = a.motion(speed, 0)
bmOwn = b.motion(speed, 0)
- let am = (if rx > 0: addr amOwn else: a.unsafeAddr)
- let bm = (if rx > 0: addr bmOwn else: b.unsafeAddr)
+ let am = (if rx > 0: addr amOwn else: a.addr)
+ let bm = (if rx > 0: addr bmOwn else: b.addr)
result.eachPixel(w, h):
let xx = (x.float32 + 0.5'f32 - fw / 2) / dip + fw / 2
let yy = (y.float32 + 0.5'f32 - fh / 2) / dip + fh / 2
@@ -869,7 +869,7 @@ proc render*(kind: TransitionKind, a, b, under: Img, p: float32, frame,
if kind != tkVhsDamage and abs(p - 0.5'f32) < 0.3'f32 and
hashi(band, step + 99, seed) < amp * 0.6'f32:
useB = not useB
- let src = (if useB: b.unsafeAddr else: a.unsafeAddr)
+ let src = (if useB: b.addr else: a.addr)
var dx = 0'f32
case kind
of tkChaos:
@@ -907,7 +907,7 @@ proc render*(kind: TransitionKind, a, b, under: Img, p: float32, frame,
let r = hashi(frame, 0, seed)
let showB = r < smooth(0.15, 0.85, p) or p > 0.85'f32
let flash = 1 + bell(p) * (hashi(frame, 1, seed) - 0.3'f32) * 0.9'f32
- let src = (if showB: b.unsafeAddr else: a.unsafeAddr)
+ let src = (if showB: b.addr else: a.addr)
result.eachPixel(w, h):
c = src[].get(x, y) * flash
@@ -977,7 +977,7 @@ proc render*(kind: TransitionKind, a, b, under: Img, p: float32, frame,
let phi = (k[2] - 180 * i.float32) * PI.float32 / 180 - turn
instants[j].side[i] = KaleidoSide(mx: mx, my: my, f0x: f0x, f0y: f0y,
r0: r0, cs: cos(phi), sn: sin(phi), scale: k[3 + i] / k[1] * fh)
- let pics = [a.unsafeAddr, b.unsafeAddr]
+ let pics = [a.addr, b.addr]
result.eachPixel(w, h):
let qx = (x.float32 + 0.5'f32 - fw / 2) / fh
let qy = (y.float32 + 0.5'f32 - fh / 2) / fh
@@ -1025,7 +1025,7 @@ proc render*(kind: TransitionKind, a, b, under: Img, p: float32, frame,
of tkTvPower:
let first = p < 0.5'f32
let q = (if first: easeIn(2 * p) else: 1 - easeOut(2 * p - 1))
- let src = (if first: a.unsafeAddr else: b.unsafeAddr)
+ let src = (if first: a.addr else: b.addr)
let sy = max(0.004'f32, 1 - clamp01(q / 0.6'f32))
let sx = max(0.004'f32, 1 - clamp01((q - 0.6'f32) / 0.4'f32))
let boost = 1 + q * 1.5'f32
@@ -1071,7 +1071,7 @@ proc render*(kind: TransitionKind, a, b, under: Img, p: float32, frame,
of tkVrMobiusZoom:
let k = bell(p)
let mixed = mixImg(a, b, mid)
- let src = mixed.unsafeAddr
+ let src = mixed.addr
result.eachPixel(w, h):
let dx = (u - 0.5'f32) * fw / fh
let dy = v - 0.5'f32
@@ -1084,7 +1084,7 @@ proc render*(kind: TransitionKind, a, b, under: Img, p: float32, frame,
of tkBurnChroma:
let ex = bell(p) * 3
let mixed = mixImg(a, b, mid)
- let src = mixed.unsafeAddr
+ let src = mixed.addr
result.eachPixel(w, h):
let cc = src[].get(x, y)
let gains = [1 + ex * 1.3'f32, 1 + ex, 1 + ex * 0.7'f32]
@@ -1230,7 +1230,7 @@ proc render*(kind: TransitionKind, a, b, under: Img, p: float32, frame,
of tkMotionCamera:
let first = p < 0.5'f32
let q = (if first: easeIn(2 * p) else: 1 - easeOut(2 * p - 1))
- let src = (if first: a.unsafeAddr else: b.unsafeAddr)
+ let src = (if first: a.addr else: b.addr)
let angle = (if first: 1'f32 else: -1'f32) * q * 0.12'f32
var moved: Img
moved.eachPixel(w, h):
@@ -1310,7 +1310,7 @@ proc render*(kind: TransitionKind, a, b, under: Img, p: float32, frame,
let hh = fh * scale / 2
if abs(px) < hw + border and abs(py) < hh + border:
if abs(px) < hw and abs(py) < hh:
- let src = (if side == 0: unsafeAddr a else: unsafeAddr b)
+ let src = (if side == 0: addr a else: addr b)
c = src[].sample(px / scale + fw / 2, py / scale + fh / 2)
else:
c = white
@@ -1323,7 +1323,7 @@ proc render*(kind: TransitionKind, a, b, under: Img, p: float32, frame,
let t = clamp01((p * 1.4'f32 - i.float32 / n.float32 * 0.4'f32))
let angle = PI.float32 * easeInOut(t)
let first = angle < PI / 2
- let src = (if first: a.unsafeAddr else: b.unsafeAddr)
+ let src = (if first: a.addr else: b.addr)
let k = abs(cos(angle))
let cx = (i.float32 + 0.5'f32) * sw
let off = (x.float32 + 0.5'f32 - cx) / max(k, 1e-3)
@@ -1483,7 +1483,7 @@ proc render*(kind: TransitionKind, a, b, under: Img, p: float32, frame,
of tkDipToBlackLegacy, tkDipToWhiteLegacy:
let dip = (if kind == tkDipToBlackLegacy: black else: white)
let first = p < 0.5'f32
- let src = (if first: a.unsafeAddr else: b.unsafeAddr)
+ let src = (if first: a.addr else: b.addr)
let k = (if first: 2 * p else: 2 - 2 * p)
result.eachPixel(w, h):
c = mix(src[].get(x, y), dip, k)
@@ -1571,7 +1571,7 @@ proc render*(kind: TransitionKind, a, b, under: Img, p: float32, frame,
of tkCrossZoomLegacy:
# Zooms into the outgoing picture, then out of the incoming one.
let z = 1 + 3 * (1 - abs(2 * p - 1))
- let src = (if p < 0.5'f32: a.unsafeAddr else: b.unsafeAddr)
+ let src = (if p < 0.5'f32: a.addr else: b.addr)
var zoomed: Img
zoomed.eachPixel(w, h):
c = src[].sample((x.float32 + 0.5'f32 - fw / 2) / z + fw / 2,
@@ -1614,7 +1614,7 @@ proc render*(kind: TransitionKind, a, b, under: Img, p: float32, frame,
# its back.
let angle = PI.float32 * p
let first = angle < PI / 2
- let src = (if first: a.unsafeAddr else: b.unsafeAddr)
+ let src = (if first: a.addr else: b.addr)
let ang = (if first: angle else: angle - PI.float32)
result.eachPixel(w, h):
let (cc, cover) = src[].turned(x.float32 + 0.5'f32, y.float32 + 0.5'f32,
@@ -1664,7 +1664,7 @@ proc render*(kind: TransitionKind, a, b, under: Img, p: float32, frame,
let fv = dy * t
if abs(fu) > fw / 2 or abs(fv) > fh / 2: continue
bestT = t
- let src = (if face == 0: a.unsafeAddr else: b.unsafeAddr)
+ let src = (if face == 0: a.addr else: b.addr)
c = src[].sample(fu + fw / 2, fv + fh / 2)
of tkConstantPower, tkExponentialFade:
diff --git a/src/render/video.nim b/src/render/video.nim
index 00b42696..aef7cb93 100644
--- a/src/render/video.nim
+++ b/src/render/video.nim
@@ -440,7 +440,7 @@ proc fromImg(im: Img, like: ptr AVFrame, ctx: ptr SwsContext): ptr AVFrame =
if av_frame_get_buffer(rgb, 32) < 0: error "Could not allocate a transition frame"
for y in 0 ..< im.h:
copyMem(cast[pointer](cast[int](rgb.data[0]) + y * rgb.linesize[0].int),
- unsafeAddr im.px[y * im.w * 3], im.w * 3)
+ addr im.px[y * im.w * 3], im.w * 3)
if AVPixelFormat(like.format).isRgb:
rgb.colorspace = like.colorspace
rgb.color_range = like.color_range
@@ -476,7 +476,7 @@ type YuvTag = tuple[space, range: cint]
const untagged: YuvTag = (2.cint, 0.cint)
-func tagOf(frame: ptr AVFrame): YuvTag = (frame.colorspace, frame.color_range)
+func tagOf(frame: ptr AVFrame): YuvTag {.inline.} = (frame.colorspace, frame.color_range)
func toYuv(color: RGBColor, tag: YuvTag): tuple[y, u, v: uint8] =
## RGB -> YUV in `tag`'s matrix and range, shared by every solid-color write
@@ -1106,9 +1106,11 @@ proc makeNewVideoFrames*(output: var OutputContainer, tl: v3, args: mainArgs,
st.kfInterval = kf.avgInterval
st.hasKfIndex = kf.hasIndex
if kf.hasIndex:
- debug &"Source {src[]}: {kf.frames.len} keyframes indexed, avg interval: {kf.avgInterval} frames"
+ debug &"Source {src[]}: {kf.frames.len} keyframes indexed, " &
+ &"avg interval: {kf.avgInterval} frames"
else:
- debug &"Source {src[]}: no index entries, using estimated interval: {kf.avgInterval} frames"
+ debug &"Source {src[]}: no index entries, using estimated " &
+ &"interval: {kf.avgInterval} frames"
if src == firstSrc and not st.isStill and
encoderCtx.pix_fmt != AV_PIX_FMT_NONE:
@@ -1204,7 +1206,8 @@ proc makeNewVideoFrames*(output: var OutputContainer, tl: v3, args: mainArgs,
proc bufArgsOf(frame: ptr AVFrame): string =
## Buffer-source args for feeding `frame` into a graph; only built when a
## graph is actually (re)configured, never on the per-frame reuse path.
- &"video_size={frame.width}x{frame.height}:pix_fmt={$AVPixelFormat(frame.format)}:time_base={graphTb}:pixel_aspect=1/1"
+ &"video_size={frame.width}x{frame.height}:" &
+ &"pix_fmt={$AVPixelFormat(frame.format)}:time_base={graphTb}:pixel_aspect=1/1"
# Scaling has stable input/output geometry, so keep one libswscale
# context instead of sending every frame through a filter graph.
@@ -1853,7 +1856,7 @@ proc makeNewVideoFrames*(output: var OutputContainer, tl: v3, args: mainArgs,
return (av_frame_clone(st.held), true)
var frame = av_frame_clone(nullFrame)
- var myStream: ptr AVStream = st.cn.video[0]
+ let myStream: ptr AVStream = st.cn.video[0]
var frameIndex = st.frameIndex
var seekThreshold = st.seekThreshold
var seekFrame = st.seekFrame
@@ -1874,7 +1877,8 @@ proc makeNewVideoFrames*(output: var OutputContainer, tl: v3, args: mainArgs,
let seekTarget = if idx >= 0: ss.observedKeyframes[idx] else: 0
if seekTarget < 0 or seekTarget > target:
let indexInfo = if ss.hasKfIndex: &"{ss.kfFrames.len} indexed" else: "no index"
- error &"Cannot seek backward: no suitable keyframe found (frameIndex: {frameIndex}, target: {target}, seekTarget: {seekTarget}, {indexInfo})"
+ error &"Cannot seek backward: no suitable keyframe found " &
+ &"(frameIndex: {frameIndex}, target: {target}, seekTarget: {seekTarget}, {indexInfo})"
debug &"Seek backward: from {frameIndex} to keyframe {seekTarget} (need frame {target})"
st.cn.seek(
videoFrameToTimestamp(seekTarget, ss.frameRate, myStream.time_base) +
diff --git a/src/resampler.nim b/src/resampler.nim
index ed501f41..77aaa8d2 100644
--- a/src/resampler.nim
+++ b/src/resampler.nim
@@ -122,7 +122,8 @@ proc resample*(resampler: var AudioResampler, frame: ptr AVFrame): seq[ptr AVFra
let extraArgs =
if frame.pts != AV_NOPTS_VALUE: ":time_base=" & $frame.time_base
else: ""
- let abufferArgs = &"sample_rate={frame.sample_rate}:sample_fmt={inputFormatName}:channel_layout={frame.ch_layout}{extraArgs}"
+ let abufferArgs = &"sample_rate={frame.sample_rate}:sample_fmt={inputFormatName}:" &
+ &"channel_layout={frame.ch_layout}{extraArgs}"
var ret = avfilter_graph_create_filter(addr resampler.abuffer, abuffer, nil,
abufferArgs.cstring, nil, resampler.graph)
@@ -130,7 +131,8 @@ proc resample*(resampler: var AudioResampler, frame: ptr AVFrame): seq[ptr AVFra
error "Could not create abuffer"
let outputFormatName = getFormatName(resampler.format)
- let aformatArgs = &"sample_rates={resampler.rate}:sample_fmts={outputFormatName}:channel_layouts={resampler.layout}"
+ let aformatArgs = &"sample_rates={resampler.rate}:sample_fmts={outputFormatName}:" &
+ &"channel_layouts={resampler.layout}"
var aformatCtx: ptr AVFilterContext = nil
ret = avfilter_graph_create_filter(addr aformatCtx, aformat, nil,
diff --git a/src/stats.nim b/src/stats.nim
index 51c9e17f..84f1fe6e 100644
--- a/src/stats.nim
+++ b/src/stats.nim
@@ -9,7 +9,7 @@ type f64 = float64
func timeFrame[T: int64 | f64](title: string, ticks: T, tb: f64,
per: string = ""): string =
- let tc = toTimecode(ticks.f64 / tb, Code.ass)
+ let tc = toTimecode(ticks.f64 / tb, ass)
let tp = (if tc.startsWith("-"): 9 else: 10)
let tcp = (if tc.startsWith("-"): 12 else: 11)
let endStr = (if per == "": "" else: " " & alignLeft(per, 7))
diff --git a/src/throttle.nim b/src/throttle.nim
deleted file mode 100644
index 2c5a054d..00000000
--- a/src/throttle.nim
+++ /dev/null
@@ -1,73 +0,0 @@
-## Cooperative pause point for the proxy/preview render. The host app keeps the
-## encoder from running more than a fixed lead ahead of the playhead by handing
-## us a "permit": the maximum output-time (in milliseconds) we're allowed to
-## reach. `checkpoint` is called once per written video frame and blocks while
-## the frame's output time is past the permit, resuming when the host raises it.
-##
-## Transport differs by build, but the protocol (a monotonically-rising int
-## watermark) is the same:
-## - native: the host writes the permit to the file named by AE_THROTTLE_FILE
-## (via tmp-file + atomic rename); we poll it.
-## - emscripten: the host exposes AE_CTRL, an Int32Array over a SharedArrayBuffer
-## (index 0 = permit ms). We Atomics.wait on it — legal because the
-## binary runs on a Worker thread, and it parks the thread with no
-## busy loop. Inert if AE_CTRL was never set up.
-
-when defined(emscripten):
- {.emit: "#include <emscripten.h>".}
-
- proc wasmThrottleActive(): cint =
- var r: cint = 0
- {.emit: """`r` = EM_ASM_INT({ return (typeof AE_CTRL !== 'undefined' && AE_CTRL) ? 1 : 0; });""".}
- r
-
- proc wasmThrottleWait(needMs: cint) =
- # The 250ms timeout makes us re-check periodically, so a missed notify can't
- # park us forever; the host's setPermit() does Atomics.notify to wake promptly.
- {.emit: """EM_ASM({
- if (typeof AE_CTRL === 'undefined' || !AE_CTRL) return;
- while (Atomics.load(AE_CTRL, 0) < $0) {
- if (Atomics.load(AE_CTRL, 1) === 1) break; // host abort flag
- Atomics.wait(AE_CTRL, 0, Atomics.load(AE_CTRL, 0), 250);
- }
- }, `needMs`);""".}
-else:
- import std/[os, strutils]
-
-type Throttle* = object
- enabled: bool
- when not defined(emscripten):
- path: string
- cachedMs: int # last permit we read; skip the file read while still under it
-
-proc initThrottle*(): Throttle =
- when defined(emscripten):
- result.enabled = wasmThrottleActive() != 0
- else:
- result.path = getEnv("AE_THROTTLE_FILE")
- result.enabled = result.path.len > 0
-
-proc checkpoint*(t: var Throttle, outputSec: float) =
- ## Block until the host permits output up to `outputSec`. No-op when throttling
- ## wasn't set up (the common case: real exports, or a host that doesn't drive it).
- if not t.enabled or outputSec < 0:
- return
- let needMs = int(outputSec * 1000.0)
- when defined(emscripten):
- wasmThrottleWait(cint(needMs))
- else:
- if t.cachedMs >= needMs:
- return
- while true:
- let permit =
- try: parseInt(strip(readFile(t.path)))
- except CatchableError: -1
- if permit < 0:
- # Unreadable (missing, or caught mid-rename): let this frame through
- # rather than risk a deadlock, but don't cache the failure — the next
- # checkpoint must re-read the file so throttling can resume.
- return
- t.cachedMs = permit
- if t.cachedMs >= needMs:
- break
- sleep(50)
diff --git a/src/timeline.nim b/src/timeline.nim
index 9b4a54ca..d7792200 100644
--- a/src/timeline.nim
+++ b/src/timeline.nim
@@ -71,7 +71,7 @@ type v3* = object
s*: seq[seq[Clip]] # Sources' subtitle streams carried through the cuts.
c*: seq[CaptionTrack] # Inline captions, rendered as a subtitle stream each.
markers*: seq[Marker]
- langs*: seq[Lang] # Video, Audio (flattened).
+ langs*: seq[Lang] # Video, Audio (flattened).
effects*: seq[Actions]
numberOfSrc*: int
clips2*: seq[Clip2] # Empty when the timeline is non-linear.
diff --git a/src/transcribe.nim b/src/transcribe.nim
index 5f1fb9cd..538d20bb 100644
--- a/src/transcribe.nim
+++ b/src/transcribe.nim
@@ -208,11 +208,11 @@ else:
proc ae_speech_free(ctx: WhisperCtx) = discard
const
- Rate = 16000 # whisper's sample rate; the graph resamples to it
- WinSize = 480 # 30ms analysis window, matching auto-editor's chunking
+ Rate = 16000 # whisper's sample rate; the graph resamples to it
+ WinSize = 480 # 30ms analysis window, matching auto-editor's chunking
SilenceGap = Rate div 2 # 0.5s of trailing silence ends an utterance
PrerollMax = Rate div 5 # keep 0.2s of pre-speech audio so onsets aren't clipped
- MinSpeech = Rate div 5 # ignore <0.2s blips (clicks, coughs)
+ MinSpeech = Rate div 5 # ignore <0.2s blips (clicks, coughs)
type OutCtx = object
f: File
@@ -360,7 +360,8 @@ proc run*(readPacket: PacketSource, audioStream: ptr AVStream,
discard av_channel_layout_copy(addr inLayout, layout)
let fmtName = av_get_sample_fmt_name(fmt)
let tb = audioStream.time_base
- let bufferArgs = &"sample_rate={rate}:sample_fmt={fmtName}:channel_layout={layout[]}:time_base={tb.num}/{tb.den}"
+ let bufferArgs = &"sample_rate={rate}:sample_fmt={fmtName}:channel_layout={layout[]}:" &
+ &"time_base={tb.num}/{tb.den}"
graph = avfilter_graph_alloc()
if graph == nil: error "out of memory"
@@ -529,7 +530,7 @@ proc transcribeFile*(input, model, language: string, threads: int,
## Write `input`'s first audio stream to `output` as an .srt with a cue per
## word: `whisper --format srt --split-words`. `model` is a whisper or
## parakeet file, or "apple"; parakeet ignores `language`.
- var container = (try: av.open(input) except IOError: error "Could not open " &
+ let container = (try: av.open(input) except IOError: error "Could not open " &
input.extractFilename)
defer: container.close()
if container.audio.len == 0: error "No audio stream found"
diff --git a/src/util/bar.nim b/src/util/bar.nim
index 2827948f..c8d6f575 100644
--- a/src/util/bar.nim
+++ b/src/util/bar.nim
@@ -45,12 +45,12 @@ type
progress: Atomic[float]
total: Atomic[float]
shouldStop: Atomic[bool]
- paused: Atomic[bool] # set by end() to halt writes
+ paused: Atomic[bool] # set by end() to halt writes
sleeping: Atomic[bool] # set by worker to acknowledge it isn't writing
title: string
lenTitle: int
begin: float
- config: ptr BarConfig # Share constant config via pointer
+ config: ptr BarConfig # Share constant config via pointer
ProgressHook* = proc (title: string, current, total: float) {.nimcall, gcsafe, raises: [].}
@@ -75,10 +75,10 @@ proc createBarString(config: BarConfig, progress: float, width: int): string =
let partCharFinal = if width - wholeWidth - 1 < 0: "" else: partChar
result = config.brackets.left &
- config.chars[^1].repeat(wholeWidth) &
- partCharFinal &
- config.chars[0].repeat(max(0, width - wholeWidth - 1)) &
- config.brackets.right
+ config.chars[^1].repeat(wholeWidth) &
+ partCharFinal &
+ config.chars[0].repeat(max(0, width - wholeWidth - 1)) &
+ config.brackets.right
proc formatProgressOutput(config: BarConfig, title: string, lenTitle, columns: int,
progress, rate, begin, currentIndex, total: float): string =
@@ -163,17 +163,17 @@ proc initBar*(barType: BarType): Bar =
var hide = false
case barType:
- of BarType.classic:
+ of classic:
icon = "⏳"
chars = @["░", "█"]
brackets = (left: "[", right: "]")
- of BarType.ascii:
+ of ascii:
icon = "& "
chars = @["-", "#"]
brackets = (left: "[", right: "]")
of BarType.machine:
machine = true
- of BarType.none:
+ of none:
hide = true
else:
discard # Use default modern style
diff --git a/src/util/color.nim b/src/util/color.nim
index 285bb06e..235d78ed 100644
--- a/src/util/color.nim
+++ b/src/util/color.nim
@@ -51,7 +51,7 @@ func toRgb*(color: RGBColor, colorspace = 1, fullRange = false): RGBColor =
return color
let (r, g, b) = yuvToRgb(color.red.float, color.green.float, color.blue.float,
yuvMatrix(colorspace), fullRange)
- func toByte(v: float): uint8 = uint8(round(clamp(v, 0.0, 1.0) * 255))
+ 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].} =
@@ -100,4 +100,5 @@ func parseColor*(hexString: string): RGBColor {.raises: [ValueError].} =
parseHex[uint8](hexValue[4..5], result.blue) != 2:
raise newException(ValueError, &"Invalid 6-digit hex color format: {hexString}")
else:
- raise newException(ValueError, &"Invalid hex color string length: {hexString}. Expected #RGB or #RRGGBB format.")
+ raise newException(ValueError,
+ &"Invalid hex color string length: {hexString}. Expected #RGB or #RRGGBB format.")
diff --git a/src/util/rational.nim b/src/util/rational.nim
index dc172667..4c98b6ab 100644
--- a/src/util/rational.nim
+++ b/src/util/rational.nim
@@ -5,11 +5,11 @@ type AVRational* {.importc, completeStruct, header: "<libavutil/rational.h>", by
const pproTicksPerSecond* = 254016000000'i64
## Premiere Pro's unit of time, which every common frame rate divides.
-func isValid*(r: AVRational): bool =
+func isValid*(r: AVRational): bool {.inline.} =
## A usable time base: positive and non-degenerate.
r.num > 0 and r.den > 0
-func toAVRational*(num: int): AVRational =
+func toAVRational*(num: int): AVRational {.inline.} =
AVRational(num: num.cint, den: 1)
func `$`*(a: AVRational): string =
diff --git a/src/util/rules.nim b/src/util/rules.nim
index 48b604ef..13fdeebc 100644
--- a/src/util/rules.nim
+++ b/src/util/rules.nim
@@ -10,16 +10,16 @@ func allowsCodec*(self: Rules, codecId: AVCodecID): bool =
var tag: cuint = 0
return av_codec_get_tag2(self.ofmt.codec_tag, codecId, addr tag) > 0
-func format*(self: Rules): ptr AVOutputFormat =
+func format*(self: Rules): ptr AVOutputFormat {.inline.} =
self.ofmt
-func defaultVid*(self: Rules): AVCodecID =
+func defaultVid*(self: Rules): AVCodecID {.inline.} =
self.ofmt.video_codec
-func defaultAud*(self: Rules): AVCodecID =
+func defaultAud*(self: Rules): AVCodecID {.inline.} =
self.ofmt.audio_codec
-proc defaultSub*(self: Rules): AVCodecID =
+proc defaultSub*(self: Rules): AVCodecID {.inline.} =
if self.ofmt.name == "mp4": ID_MOV_TEXT else: self.ofmt.subtitle_codec
func holdsVideo*(name: string): bool =
diff --git a/src/util/speedmap.nim b/src/util/speedmap.nim
index b19e81ef..3fe203e9 100644
--- a/src/util/speedmap.nim
+++ b/src/util/speedmap.nim
@@ -9,10 +9,10 @@ from std/math import round
import ../action
type SpeedMap* = object
- mean*: float64 # the clip's speed as its length and offset reckon it
- ramp*: bool # whether any of its speed actions is a ramp
- tau: seq[float64] # time fraction reached at media fraction i / speedSteps
- scale: float64 # media fraction per time fraction, over the speed
+ mean*: float64 # the clip's speed as its length and offset reckon it
+ ramp*: bool # whether any of its speed actions is a ramp
+ tau: seq[float64] # time fraction reached at media fraction i / speedSteps
+ scale: float64 # media fraction per time fraction, over the speed
first, last: float64 # the speed at either end, past which it holds
func speedOf*(effects: Actions, u: float64, varispeed: set[bool] = {false, true}):
diff --git a/src/util/term.nim b/src/util/term.nim
index 52ae4288..caeff7e8 100644
--- a/src/util/term.nim
+++ b/src/util/term.nim
@@ -2,7 +2,7 @@ import std/terminal
when defined(emscripten):
{.emit: "#include <emscripten.h>".}
- proc terminalWidth*(): int = 80
+ proc terminalWidth*(): int {.inline.} = 80
proc wasmProgressWrite*(text: cstring) =
{.emit: """EM_ASM({ out(UTF8ToString($0) + '\r'); }, `text`);""".}
else:
diff --git a/src/util/timecode.nim b/src/util/timecode.nim
index 7c67c0b6..a3bab12a 100644
--- a/src/util/timecode.nim
+++ b/src/util/timecode.nim
@@ -10,11 +10,11 @@ type Timecode* = object
h*, m*, s*, f*: int64
drop*: bool ## written with a `;`, `.` or `,` separator
-func timecodeBase*(tb: AVRational): int64 =
+func timecodeBase*(tb: AVRational): int64 {.inline.} =
## The frames a second holds in timecode: 30 for 29.97, 24 for 23.976.
max(1'i64, int64(ceil(tb.float64 - 1e-9)))
-func dropPerMinute(base: int64): int64 =
+func dropPerMinute(base: int64): int64 {.inline.} =
## 29.97 skips two numbers a minute, 59.94 four.
base div 15
diff --git a/src/util/xml.nim b/src/util/xml.nim
index a0c70c6a..a2176b27 100644
--- a/src/util/xml.nim
+++ b/src/util/xml.nim
@@ -25,30 +25,30 @@ type
attrs*: XmlAttributes
children: seq[XmlNode]
-func newElement*(tag: string): XmlNode =
+func newElement*(tag: string): XmlNode {.inline.} =
XmlNode(str: tag)
-func newText*(text: string): XmlNode =
+func newText*(text: string): XmlNode {.inline.} =
XmlNode(kind: xnText, str: text)
-func newVerbatimText*(text: string): XmlNode =
+func newVerbatimText*(text: string): XmlNode {.inline.} =
XmlNode(kind: xnVerbatimText, str: text)
func newXmlTree*(tag: string, children: openArray[XmlNode],
- attrs: XmlAttributes = @[]): XmlNode =
+ attrs: XmlAttributes = @[]): XmlNode {.inline.} =
XmlNode(str: tag, attrs: attrs, children: @children)
-func toXmlAttributes*(pairs: varargs[(string, string)]): XmlAttributes =
+func toXmlAttributes*(pairs: varargs[(string, string)]): XmlAttributes {.inline.} =
@pairs
-func add*(parent, child: XmlNode) =
+func add*(parent, child: XmlNode) {.inline.} =
parent.children.add child
-func len*(n: XmlNode): int =
+func len*(n: XmlNode): int {.inline.} =
## The number of children.
n.children.len
-func tag*(n: XmlNode): string =
+func tag*(n: XmlNode): string {.inline.} =
n.str
iterator items*(n: XmlNode): XmlNode =