Skip to content

Effort free video editing!

7.9 KB
Raw Blame
## The edit rendered frame by frame for a player, as an export would render
## it (effects, overlays, transitions, every track composited and mixed),
## with nothing encoded.

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
  output: OutputContainer
  encoder: ptr AVCodecContext
  video, audio: iterator(): (ptr AVFrame, int64)
  stop: Atomic[bool]
  audioAt: int # samples into the timeline that the next audio starts at
  tb*: AVRational ## the timeline's frame rate
  sampleRate*: int ## audio is interleaved float32 stereo at this rate
  quarterTurns*: int ## clockwise turns to show frames upright, as the output's display matrix says
  sar*: AVRational ## the output's sample aspect ratio; scaled frames don't carry it
  hasVideo*, hasAudio*: bool

proc openPreview*(args: sink mainArgs, startSeconds, scale: float64,
    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`).
  ## 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 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
  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()
  let tb = r.renderTl.tb
  r.tb = tb
  r.sampleRate = r.renderTl.sr.int
  let start = clamp(int64(round(startSeconds * tb.float64)), 0, max(r.renderTl.len - 1, 0))
  if r.renderTl.hasBaseVideo:
    # Frames come unturned; the export carries the template's display matrix.
    if r.renderTl.templateFile != nil:
      let vids = r.cache.getContainer(r.renderTl.templateFile).video
      if vids.len > 0: r.quarterTurns = quarterTurns(vids[0].codecpar)
    r.output = openWrite("preview.mkv")
    var stream: ptr AVStream
    (r.encoder, stream, r.video) = makeNewVideoFrames(r.output, addr r.renderTl,
      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):
    let fromSample = audioSampleSpan(start, 0, r.renderTl.sr, tb).start
    r.audio = makeAudioFrames(AV_SAMPLE_FMT_FLT, addr r.renderTl, 1024,
      toSeq(0 ..< r.renderTl.a.len), Norm(kind: nkNull), r.cache,
      fromSample, addr r.stop)
    r.audioAt = fromSample
    r.hasAudio = true
  r

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) =
    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)

proc nextAudio*(r: PreviewRender): tuple[frame: ptr AVFrame, seconds: float64] =
  ## The next chunk of audio and when it starts, or nil at the end. The
  ## caller frees the frame.
  if not r.hasAudio or finished(r.audio): return (nil, 0.0)
  let (frame, _) = r.audio()
  if frame == nil or finished(r.audio): return (nil, 0.0)
  result = (frame, r.audioAt.float64 / r.sampleRate.float64)
  r.audioAt += frame.nb_samples

proc close*(r: PreviewRender) =
  ## Stop early: each renderer frees what it holds when next resumed.
  r.stop.store(true)
  # 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.
    while not finished(r.audio):
      var (frame, _) = r.audio()
      if frame != nil: av_frame_free(addr frame)
  if r.encoder != nil: avcodec_free_context(addr r.encoder)
  if r.output.formatCtx != nil: r.output.abandon()
  for i in r.sourceEffects ..< r.renderTl.effects.len:
    r.renderTl.effects[i].free()
  freeActions(r.args, r.tl)
  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()