Skip to content

Effort free video editing!

Let a preview session keep sources across renders

WyattBlue433d261da74c
diff --git a/src/conductor.nim b/src/conductor.nim
index 355154e7..8fae6d93 100644
--- a/src/conductor.nim
+++ b/src/conductor.nim
@@ -299,7 +299,7 @@ proc setVideoCodec(inCodec: string, src: MediaInfo, rule: Rules,
return $avcodec_get_name(rule.defaultVid)
proc applyAdds(tl: var v3, args: var mainArgs,
- interner: var StringInterner) {.raises: [AutoEditorError].} =
+ interner: var StringInterner, probes: Probes) {.raises: [AutoEditorError].} =
## Inject `add:` overlays as new layers. Each spec overlays its source on
## every base-layer (v[0]) clip whose section matches the spec's selector
## (0 = silent, 1 = normal), spanning the same timeline range. With
@@ -328,7 +328,7 @@ proc applyAdds(tl: var v3, args: var mainArgs,
if spec.generator.len > 0:
soundOnly[i] = isAudioGen(spec)
else:
- mis[i] = initMediaInfo(spec.path)
+ mis[i] = probes.probe(spec.path)
soundOnly[i] = mis[i].v.len == 0
# Audio-only timeline: synthesize a background base video track so the
@@ -423,7 +423,8 @@ proc applyAdds(tl: var v3, args: var mainArgs,
args.mixAudioStreams = true
tl.updateNumberOfSrc()
-proc applyLayers(tl: var v3, args: var mainArgs, interner: var StringInterner) =
+proc applyLayers(tl: var v3, args: var mainArgs, interner: var StringInterner,
+ probes: Probes) =
## Composite `args.layers` over the edit as the desktop app's
## buildOverlayJson does: the last layer lowest, the first on top, each
## clamped to [start, finish) of the output.
@@ -451,7 +452,7 @@ proc applyLayers(tl: var v3, args: var mainArgs, interner: var StringInterner) =
except ActionParseError as e:
error e.msg
let src = interner.intern(spec.path)
- let mi = initMediaInfo(spec.path)
+ let mi = probes.probe(spec.path)
var track: seq[Clip]
if spec.followCuts and not mi.isStill:
# The base's sections, speeds included, so the layer stays in step
@@ -496,13 +497,13 @@ type BuiltTimeline* = object
lengths*: MediaLengths ## of the inputs whose length the edit had to find
proc buildTimeline*(args: var mainArgs, audio: AudioSettings,
- interner: var StringInterner, bar: Bar): BuiltTimeline =
+ interner: var StringInterner, bar: Bar, probes: Probes = nil): BuiltTimeline =
## Analyze the inputs and decide every cut without exporting anything.
## Release with `freeActions(args, result.tl)` when done.
var tlV3: v3
var usePath = ""
var mi: MediaInfo
- var lengths: MediaLengths
+ var lengths = (if probes != nil: probes.lengths else: default(MediaLengths))
var markersPlaced = false
if args.inputs.len == 0 and not stdin.isatty():
let stdinContent = readAll(stdin)
@@ -543,8 +544,11 @@ proc buildTimeline*(args: var mainArgs, audio: AudioSettings,
var appended: Table[(int, int), Actions]
for i in 0 ..< args.inputs.len:
- let container = (try: av.open(args.inputs[i]) except IOError as e: error e.msg)
- defer: container.close()
+ let container =
+ if probes != nil: probes.container(args.inputs[i])
+ else: (try: av.open(args.inputs[i]) except IOError as e: error e.msg)
+ defer:
+ if probes == nil: container.close()
if i == 0 and args.frameRate == AVRational(num: 0, den: 0):
if container.video.len > 0:
@@ -632,7 +636,9 @@ proc buildTimeline*(args: var mainArgs, audio: AudioSettings,
if a.setActionRef == sIdx:
a.selector = aIdx
- let inputMi = initMediaInfo(container.formatContext, args.inputs[i])
+ let inputMi =
+ if probes != nil: probes.probe(args.inputs[i])
+ else: initMediaInfo(container.formatContext, args.inputs[i])
if not tlInitialized:
mi = inputMi
@@ -647,8 +653,8 @@ proc buildTimeline*(args: var mainArgs, audio: AudioSettings,
tlV3.mapMarkers(args.markers)
markersPlaced = true
- applyAdds(tlV3, args, interner)
- applyLayers(tlV3, args, interner)
+ applyAdds(tlV3, args, interner, probes)
+ applyLayers(tlV3, args, interner, probes)
tlV3.applyArgs(args, audio)
if args.transition.sign > 0:
tlV3.addTransitions(args.transitionKind,
@@ -659,6 +665,7 @@ proc buildTimeline*(args: var mainArgs, audio: AudioSettings,
if args.markers.len > 0 and not markersPlaced:
warning "Markers in source time only apply to media inputs; left out"
+ if probes != nil: probes.lengths = lengths
BuiltTimeline(tl: tlV3, usePath: usePath, mi: mi, lengths: lengths)
type EditPlan* = object
diff --git a/src/media.nim b/src/media.nim
index 88b4c087..975b921d 100644
--- a/src/media.nim
+++ b/src/media.nim
@@ -1,4 +1,4 @@
-import std/math
+import std/[math, os, tables, times]
import ./[av, ffmpeg, log]
import ./lib/lang
import ./util/rational
@@ -160,6 +160,75 @@ proc initMediaInfo*(path: string): MediaInfo =
result = initMediaInfo(formatCtx, path)
avformat_close_input(addr formatCtx)
+type FileStamp* = tuple[size: int64, mtime: Time]
+
+proc fileStamp*(path: string): FileStamp =
+ ## `path`'s size and modification time; (-1, 0) when it can't be read.
+ try:
+ let info = getFileInfo(path)
+ (info.size, info.lastWriteTime)
+ except OSError:
+ (-1'i64, Time())
+
+type Probes* = ref object
+ ## Files a timeline is built from, opened and probed once and kept for the
+ ## next build. Whoever keeps it drops a path whose file has changed.
+ cns: Table[string, InputContainer]
+ infos: Table[string, MediaInfo]
+ stamps: Table[string, FileStamp] # each path's, from just before it was read
+ lengths*: MediaLengths
+
+proc newProbes*(): Probes = Probes()
+
+proc note(p: Probes, path: string) =
+ # Taken before reading, so a write landing mid-read shows as a change.
+ if path notin p.stamps: p.stamps[path] = fileStamp(path)
+
+proc container*(p: Probes, path: string): InputContainer =
+ ## `path` opened. Analyses rewind it before reading, so builds can share it.
+ p.cns.withValue(path, cn): return cn[]
+ p.note(path)
+ result = (try: av.open(path) except IOError as e: error e.msg)
+ p.cns[path] = result
+
+proc probe*(p: Probes, path: string): MediaInfo =
+ ## `path`'s media info, probed once while `p` keeps it. `p` may be nil.
+ if p == nil: return initMediaInfo(path)
+ p.infos.withValue(path, mi): return mi[]
+ p.note(path)
+ let cn = p.cns.getOrDefault(path)
+ result =
+ if cn.formatContext != nil: initMediaInfo(cn.formatContext, path)
+ else: initMediaInfo(path)
+ p.infos[path] = result
+
+proc stampOf*(p: Probes, path: string): FileStamp =
+ ## The stamp `path` had when `p` first read it, or its stamp now.
+ p.stamps.withValue(path, st): return st[]
+ fileStamp(path)
+
+iterator paths*(p: Probes): string =
+ ## Every path `p` holds something for.
+ # Copied first, so a caller can forget paths as it goes.
+ var held: seq[string]
+ for path in p.stamps.keys: held.add path
+ for path in held: yield path
+
+proc forget*(p: Probes, path: string) =
+ if path in p.cns:
+ p.cns[path].close()
+ p.cns.del path
+ p.infos.del path
+ p.stamps.del path
+ p.lengths.del path
+
+proc close*(p: Probes) =
+ for cn in p.cns.values: cn.close()
+ p.cns.clear()
+ p.infos.clear()
+ p.stamps.clear()
+ p.lengths.clear()
+
func makeSaneTimebase*(tb: AVRational): AVRational {.raises: [].} =
# A 0/0 rate (no declared fps) is NaN as a float; av_d2q(NaN) is degenerate.
if not tb.isValid:
diff --git a/src/render/preview.nim b/src/render/preview.nim
index 5665da4d..1d4a30b2 100644
--- a/src/render/preview.nim
+++ b/src/render/preview.nim
@@ -2,16 +2,86 @@
## it (effects, overlays, transitions, every track composited and mixed),
## with nothing encoded.
-import std/[atomics, math, sequtils]
-import ../[action, av, conductor, ffmpeg, log, timeline]
+import std/[atomics, math, sequtils, sets, tables]
+import ../[action, av, conductor, ffmpeg, log, media, timeline]
import ../util/[bar, rational]
import ./[audio, format, video]
+type
+ PreviewSession* = ref object
+ ## What renders of one project share: the files opened and probed to
+ ## build its timeline, and each source's decoders, with the frame each
+ ## last decoded. A render at the frame the last one showed (a paused frame
+ ## re-rendered after an edit) then opens and decodes nothing. A file that
+ ## changes on disk is reopened. Drive it from one thread, one render open
+ ## at a time.
+ interner: StringInterner
+ probes: Probes
+ cache: MediaCache
+ sources: VideoSources
+ stamps: Table[string, FileStamp] # of the paths the last render used
+
+proc newPreviewSession*(): PreviewSession =
+ PreviewSession(probes: newProbes(), cache: newMediaCache(),
+ sources: newVideoSources())
+
+proc forget*(s: PreviewSession, path: string) =
+ ## Reopen `path` at the next render, as when it changed in a way its size
+ ## and modification time don't show. `path` is spelled as in the edit's
+ ## inputs or layers; another spelling of the same file matches nothing.
+ let src = s.interner.getOrDefault(path)
+ if src != nil:
+ s.sources.forget(src)
+ if src in s.cache.cns:
+ s.cache.cns[src].close()
+ s.cache.cns.del src
+ s.probes.forget(path)
+ s.stamps.del path
+
+proc close*(s: PreviewSession) =
+ ## Free the session. Close its render first.
+ s.sources.close()
+ s.cache.close()
+ s.probes.close()
+ s.stamps.clear()
+ s.interner.cleanup()
+
+proc forgetAll(s: PreviewSession) =
+ var held: seq[string]
+ for path in s.stamps.keys: held.add path
+ for path in s.probes.paths:
+ if path notin held: held.add path
+ for src in s.cache.cns.keys:
+ if src[] notin held: held.add src[]
+ for path in held: s.forget(path)
+
+proc dropChanged(s: PreviewSession) =
+ var changed: seq[string]
+ for path, was in s.stamps:
+ if fileStamp(path) != was: changed.add path
+ for path in changed: s.forget(path)
+
+proc dropUnused(s: PreviewSession, used: seq[ptr string]) =
+ ## Forget what the edit no longer uses, and stamp what it does.
+ var usedPaths: seq[string]
+ for src in used: usedPaths.add src[]
+ var stale: seq[string]
+ # A source's decoders are only made after its container is in the cache.
+ for src in s.cache.cns.keys:
+ if src[] notin usedPaths: stale.add src[]
+ for path in s.probes.paths:
+ if path notin usedPaths and path notin stale: stale.add path
+ for path in stale: s.forget(path)
+ for path in usedPaths:
+ if path notin s.stamps: s.stamps[path] = s.probes.stampOf(path)
+
type PreviewRender* = ref object
## Video and audio are pulled separately so the caller can keep them in
## step. Single-threaded: drive it from one thread.
args: mainArgs
interner: StringInterner
+ session: PreviewSession
+ failed: bool # a frame raised partway through decoding
tl, renderTl: v3
sourceEffects: int
cache: MediaCache
@@ -27,18 +97,33 @@ type PreviewRender* = ref object
hasVideo*, hasAudio*: bool
proc openPreview*(args: sink mainArgs, startSeconds, scale: float64,
- withAudio = true): PreviewRender =
+ withAudio = true, session: PreviewSession = nil): PreviewRender =
## The edit `args` describes, from `startSeconds` into the result, at
## `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`).
- let r = PreviewRender(args: args)
+ ## With `session`, sources opened and decoded by its earlier renders are
+ ## reused, and stay open in it after `close`.
+ let r = PreviewRender(args: args, session: session)
# 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,
- initBar(BarType.none))
+ let audio = AudioSettings(layout: "stereo")
+ let built =
+ if session != nil:
+ session.dropChanged()
+ buildTimeline(r.args, audio, session.interner, initBar(BarType.none),
+ session.probes)
+ else:
+ buildTimeline(r.args, audio, r.interner, initBar(BarType.none))
r.tl = built.tl
- r.cache = newMediaCache()
+ if session != nil:
+ var used = r.tl.uniqueSources.toSeq
+ if r.tl.templateFile != nil and r.tl.templateFile notin used:
+ used.add r.tl.templateFile
+ session.dropUnused(used)
+ r.cache = session.cache
+ else:
+ r.cache = newMediaCache()
r.tl.dropUndecodableAudio(r.cache)
r.sourceEffects = r.tl.effects.len
r.renderTl = r.tl.bakeTransitions()
@@ -54,7 +139,8 @@ proc openPreview*(args: sink mainArgs, startSeconds, scale: float64,
r.output = openWrite("preview.mkv")
var stream: ptr AVStream
(r.encoder, stream, r.video) = makeNewVideoFrames(r.output, r.renderTl,
- r.args, video, r.cache, start, addr r.stop)
+ r.args, video, r.cache, start, addr r.stop,
+ if session != nil: session.sources else: nil)
r.sar = r.encoder.sample_aspect_ratio
r.hasVideo = true
if withAudio and r.renderTl.a.anyIt(it.len > 0):
@@ -70,7 +156,11 @@ proc nextVideo*(r: PreviewRender): tuple[frame: ptr AVFrame, seconds: float64] =
## The next frame and when it shows, or nil at the end. The frame stays the
## render's: it's valid until the next call.
if not r.hasVideo or finished(r.video): return (nil, 0.0)
- let (frame, index) = r.video()
+ let (frame, index) =
+ try: r.video()
+ except CatchableError:
+ r.failed = true
+ raise
if frame == nil or finished(r.video): return (nil, 0.0)
(frame, (index * r.tb.den).float64 / r.tb.num.float64)
@@ -86,7 +176,8 @@ proc nextAudio*(r: PreviewRender): tuple[frame: ptr AVFrame, seconds: float64] =
proc close*(r: PreviewRender) =
## Stop early: each renderer frees what it holds when next resumed.
r.stop.store(true)
- if r.hasVideo:
+ # An iterator that raised isn't finished, and resuming it raises again.
+ if r.hasVideo and not r.failed:
while not finished(r.video): discard r.video()
if r.hasAudio:
# Frames already resampled come out first.
@@ -98,5 +189,10 @@ proc close*(r: PreviewRender) =
for i in r.sourceEffects ..< r.renderTl.effects.len:
r.renderTl.effects[i].free()
freeActions(r.args, r.tl)
- if r.cache != nil: r.cache.close()
- r.interner.cleanup()
+ if r.session == nil:
+ if r.cache != nil: r.cache.close()
+ r.interner.cleanup()
+ elif r.failed:
+ # A decode that stopped partway leaves its decoder's position unknown,
+ # so the next render starts the session's sources over.
+ r.session.forgetAll()
diff --git a/src/render/video.nim b/src/render/video.nim
index 2c26c68b..aea04bb9 100644
--- a/src/render/video.nim
+++ b/src/render/video.nim
@@ -252,6 +252,37 @@ proc resetDeint(st: DecState) =
if st.deintNext != nil:
av_frame_free(addr st.deintNext)
+type VideoSources* = ref object
+ ## Each source's decoders, with the frame each last gave, and its decoded
+ ## still, handed from one render to the next so a render at a frame the
+ ## last one reached doesn't seek and decode again. A source's first decoder
+ ## reads the media cache's container for it, so keep them together: forget
+ ## a source here when its container leaves the cache.
+ srcs: Table[ptr string, SrcState]
+
+proc free(s: SrcState) =
+ if s.still != nil:
+ av_frame_free(addr s.still)
+ for d in s.decoders:
+ if d.held != nil:
+ av_frame_free(addr d.held)
+ d.resetDeint()
+ avcodec_free_context(addr d.decoder)
+ if d.ownsCn: d.cn.close()
+ s.decoders.setLen(0)
+
+proc newVideoSources*(): VideoSources = VideoSources()
+
+proc forget*(vs: VideoSources, src: ptr string) =
+ ## Drop what `src` holds, as when its file changes.
+ if src in vs.srcs:
+ vs.srcs[src].free()
+ vs.srcs.del src
+
+proc close*(vs: VideoSources) =
+ for s in vs.srcs.values: s.free()
+ vs.srcs.clear()
+
proc nextFrame(st: DecState, stream: ptr AVStream, frame: ptr AVFrame): bool =
## Decode the next frame into `frame`, false at the end of the stream.
## No encoder here codes fields (VideoToolbox can't at all), and effects and
@@ -954,15 +985,18 @@ func scaledVideoResolution*(resolution: (int32, int32),
proc makeNewVideoFrames*(output: var OutputContainer, tl: v3, args: mainArgs,
video: VideoSettings, myCache: MediaCache, startIndex = 0'i64,
- stop: ptr Atomic[bool] = nil):
+ stop: ptr Atomic[bool] = nil, keep: VideoSources = nil):
(ptr AVCodecContext, ptr AVStream, iterator(): (ptr AVFrame, int64)) =
## Frames from `startIndex` on. A set `stop` ends the iterator at its next
## call, freeing what it holds (a preview abandons a render this way).
+ ## With `keep`, sources' decoders come from it and stay in it at the end,
+ ## for the next render to pick up where this one left off.
# One state object per source (decoders, seek bookkeeping, still/held frame
# caches, loop accounting). Still-image sources (overlay logos/watermarks)
# decode a single frame that is held for the clip's whole duration in `still`.
- var srcs = initTable[ptr string, SrcState]()
+ let sources = (if keep != nil: keep else: newVideoSources())
+ template srcs: untyped = sources.srcs
# Within a single timeline frame, two layers can reference the same source at
# the same source-frame index (e.g. a clip composited over itself). The shared
# per-source decoder can only be at one position, so memoize the raw decoded
@@ -982,6 +1016,10 @@ proc makeNewVideoFrames*(output: var OutputContainer, tl: v3, args: mainArgs,
# getContainer turns a missing/unreadable source (e.g. `add:gone.mp4`)
# into a clean error instead of an unhandled IOError.
discard myCache.getContainer(src)
+ if src in srcs:
+ # Kept from an earlier render, whose frame numbers usedAt counts in.
+ for d in srcs[src].decoders: d.usedAt = -1
+ continue
# Per-source state with mutable-decode defaults. Decoding always begins on a
# keyframe, so frame 0 is always a valid seek point (observedKeyframes starts
@@ -1899,6 +1937,9 @@ proc makeNewVideoFrames*(output: var OutputContainer, tl: v3, args: mainArgs,
avcodec_flush_buffers(st.decoder)
st.resetDeint()
st.lastSeekTarget = seekTarget
+ # The threshold guards the frames past an earlier seek-ahead; behind
+ # them now, a later far request would decode all the way up to it.
+ seekThreshold = min(seekThreshold, seekTarget)
seekWant = want
frameIndex = min(seekTarget, target - 1)
@@ -2539,16 +2580,5 @@ proc makeNewVideoFrames*(output: var OutputContainer, tl: v3, args: mainArgs,
for _, f in decodedCache:
var df = f
av_frame_free(addr df)
- for _, s in srcs:
- if s.still != nil:
- var sf = s.still
- av_frame_free(addr sf)
- for d in s.decoders:
- if d.held != nil:
- var hf = d.held
- av_frame_free(addr hf)
- d.resetDeint()
- var p = d.decoder
- avcodec_free_context(addr p)
- if d.ownsCn: d.cn.close()
+ if keep == nil: sources.close()
debug &"Total frames avoided decoding via seeks: {framesSaved}")