Skip to content

Effort free video editing!

32.6 KB
Raw Blame
import std/[algorithm, options, os, sets, strformat, tables]
from std/math import round, ceil, exp, sin, PI
import ./[action, av, ffmpeg, log, media, wavutil]
import ./lib/[cliputil, lang, paths, transitions]
import ./util/[color, parse, rational, speedmap]

type v1* = object
  chunks*: seq[(int64, int64, float64)]
  source*: string
  tb*: AVRational

type Clip2* = object
  start*: int64
  `end`*: int64
  effect*: uint32

type v2* = object
  source*: string
  tb*: AVRational
  effects*: seq[Actions]
  clips*: seq[Clip2]

type Clip* = object
  src*: ptr string
  start*: int64
  dur*: int64
  offset*: int64
  stream*: int16
  effects*: uint32 # Reference to global effects in Timeline.

type Caption* = object
  ## A cue shown from `start` for `dur` timeline frames.
  start*: int64
  dur*: int64
  text*: string

type CaptionTrack* = object
  lang*: Lang
  cues*: seq[Caption]

export transitions

type
  TransitionAlignment* = enum
    taStart, taCenter, taEnd
  Transition* = object
    at*: int64
    dur*: int64
    easeIn*, easeOut*: float32 = defaultEase ## a dissolve's curve, 0 to 100
    kind*: TransitionKind
    alignment*: TransitionAlignment
  TransitionLink* = object
    incoming*: int32 = -1
    outgoing*: int32 = -1
  TransitionWindow* = object
    ## A baked video transition: the frames from `start` for `dur` on its
    ## track blend the clips there by `kind`.
    start*, dur*: int64
    easeIn*, easeOut*: float32 = defaultEase
    kind*: TransitionKind
    alignment*: TransitionAlignment

type v3* = object
  layout*: ref AVChannelLayout
  res*: (int32, int32)
  tb*: AVRational
  bg*: RGBColor
  sr*: cint
  v*: seq[seq[Clip]]
  a*: seq[seq[Clip]]
  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).
  effects*: seq[Actions]
  numberOfSrc*: int
  clips2*: seq[Clip2] # Empty when the timeline is non-linear.
  templateFile*: ptr string
  vt*: seq[seq[Transition]]
  at*: seq[seq[Transition]]
  windows*: seq[seq[TransitionWindow]] # per video track, set by bakeTransitions

proc `=copy`*(dest: var v3, src: v3) {.error:
  "a v3 is too big to copy implicitly: move it, borrow it, or `clone` it".}
proc `=dup`*(src: v3): v3 {.error:
  "a v3 is too big to copy implicitly: move it, borrow it, or `clone` it".}

func clone*(tl: v3): v3 =
  ## The one way to copy a timeline.
  for dst, src in fields(result, tl):
    dst = src

func len*(self: v3): int64 {.raises: [].} =
  result = 0
  for clips in self.v:
    if len(clips) > 0:
      result = max(result, clips[^1].start + clips[^1].dur)
  for clips in self.a:
    if len(clips) > 0:
      result = max(result, clips[^1].start + clips[^1].dur)

func clipFrameAt*(clip: Clip, map: SpeedMap, media: float64): int64 =
  ## The timeline frame showing `media`, a position in the clip's source as
  ## timeline frames from the source's start. `map` is the clip's speed map.
  let local = media / map.mean - clip.offset.float64
  let t = (if map.ramp and clip.dur > 0:
    clip.dur.float64 * map.timeAt(local / clip.dur.float64) else: local)
  clip.start + int64(round(t))

func firstSource*(self: v3): ptr string {.raises: [].} =
  for vlayer in self.v:
    if vlayer.len > 0 and vlayer[0].src != nil:
      return vlayer[0].src
  for alayer in self.a:
    if alayer.len > 0 and alayer[0].src != nil:
      return alayer[0].src
  return nil

func uniqueSources*(self: v3): HashSet[ptr string] {.raises: [].} =
  for vlayer in self.v:
    for video in vlayer:
      if video.src != nil:
        result.incl(video.src)
  for alayer in self.a:
    for audio in alayer:
      if audio.src != nil:
        result.incl(audio.src)

proc updateNumberOfSrc*(self: var v3) {.raises: [].} =
  self.numberOfSrc = self.uniqueSources.len

proc rescaleKt(kt: var seq[KfTime], k: float64): bool =
  for t in kt.mitems:
    if t.unit == kuFrames:
      t.at = float32(round(t.at.float64 * k))
      result = true

proc rescaleAction(a: var Action, k: float64): bool =
  if a.hasEase and a.easeDurUnit == duFrames:
    a.easeDur = max(1'f32, float32(round(a.easeDur.float64 * k)))
    result = true
  case a.kind
  of actZoom, actBlur, actOpacity, actBrightness, actVolume:
    result = rescaleKt(a.kt, k) or result
  of actPos:
    result = rescaleKt(a.pxKt, k) or result
    result = rescaleKt(a.pyKt, k) or result
    result = rescaleKt(a.pscaleKt, k) or result
  of actPixelate:
    result = rescaleKt(a.pixWKt, k) or result
    result = rescaleKt(a.pixHKt, k) or result
  else: discard

proc rescale*(self: var v3, tb: AVRational) {.raises: [ActionParseError].} =
  if not tb.isValid or (tb.num == self.tb.num and tb.den == self.tb.den):
    return
  let k = float64(tb.num) * float64(self.tb.den) / (float64(tb.den) * float64(self.tb.num))
  func at(x: int64): int64 = int64(round(x.float64 * k))
  proc span(start, dur: var int64) =
    let stop = at(start + dur)
    start = at(start)
    dur = max(stop - start, 1)

  var repacked: seq[(int, Actions)]
  try:
    for i, e in self.effects:
      if not (e.isCut or e.isEmpty):
        var list: seq[Action]
        var changed = false
        for a in e:
          var a = a
          changed = rescaleAction(a, k) or changed
          list.add a
        if changed: repacked.add (i, newActions(list))
  except ActionParseError as err:
    for (_, e) in repacked: free(e)
    raise err
  for (i, e) in repacked:
    free(self.effects[i])
    self.effects[i] = e

  for tracks in [addr self.v, addr self.a, addr self.s]:
    for track in tracks[].mitems:
      for clip in track.mitems:
        clip.offset = at(clip.offset)
        span(clip.start, clip.dur)
  for clip in self.clips2.mitems:
    let stop = at(clip.`end`)
    clip.start = at(clip.start)
    clip.`end` = max(stop, clip.start + 1)
  for track in self.c.mitems:
    for cue in track.cues.mitems:
      span(cue.start, cue.dur)
  for tracks in [addr self.vt, addr self.at]:
    for track in tracks[].mitems:
      for t in track.mitems:
        t.at = at(t.at)
        t.dur = max(at(t.dur), 1)
        if t.alignment == taCenter: t.dur = max(t.dur div 2 * 2, 2)
  for track in self.windows.mitems:
    for w in track.mitems:
      span(w.start, w.dur)
  self.tb = tb

func hasBaseVideo*(tl: v3): bool {.inline.} =
  ## Whether the bottom video track has a clip; tracks can be empty.
  tl.v.len > 0 and tl.v[0].len > 0

func hasBaseAudio*(tl: v3): bool {.inline.} =
  ## Whether the first audio track has a clip; tracks can be empty.
  tl.a.len > 0 and tl.a[0].len > 0

func timelineIsEmpty(self: v3): bool =
  not self.hasBaseVideo and not self.hasBaseAudio

func isLinear*(self: v3): bool {.raises: [].} =
  return self.clips2.len > 0 or self.timelineIsEmpty

proc chunkify(arr: seq[int], effects: seq[Actions]): seq[(int64, int64, int, Actions)] =
  if arr.len == 0:
    return @[]

  var start: int64 = 0
  var j: int64 = 1
  while j < arr.len:
    if arr[j] != arr[j - 1]:
      result.add (start, j, arr[j-1], effects[arr[j - 1]])
      start = j
    inc j
  result.add (start, arr.len.int64, arr[j-1], effects[arr[j - 1]])

proc decodableAudio(mi: MediaInfo): seq[int] =
  for i in 0 ..< mi.a.len:
    if canDecode(mi.a[i].codecId):
      result.add i
    else:
      warning &"Skipping audio stream {i}: no decoder for {avcodec_get_name(mi.a[i].codecId)}"

proc mutHelper(tl: var v3, mi: MediaInfo, clips: seq[Clip]) =
  if mi.v.len > 0:
    var vlayer = newSeqOfCap[Clip](clips.len)
    for clip in clips:
      var videoClip = clip
      videoClip.stream = 0
      vlayer.add videoClip
    tl.v.add vlayer
    tl.langs.add mi.v[0].lang

  let audioStreams = mi.decodableAudio

  for i in audioStreams:
    var alayer = newSeqOfCap[Clip](clips.len)
    for clip in clips:
      var audioClip = clip
      audioClip.stream = i.int16
      alayer.add audioClip
    tl.a.add alayer
    tl.langs.add mi.a[i].lang

  for i in 0 ..< mi.s.len:
    var slayer = newSeqOfCap[Clip](clips.len)
    for clip in clips:
      var subtitleClip = clip
      subtitleClip.stream = i.int16
      slayer.add subtitleClip
    tl.s.add slayer

  if tl.timelineIsEmpty:
    error "Timeline is empty, nothing to do."

  if audioStreams.len > 0:
    tl.sr = mi.a[audioStreams[0]].sampleRate
    tl.layout = initLayout(mi.a[audioStreams[0]].layout)
  else:
    tl.sr = 48000
    tl.layout = initLayout("stereo")
  tl.updateNumberOfSrc()


proc linearClips(src: ptr string, effects: seq[Actions], actionIndex: seq[int],
    start: int64, clips2: var seq[Clip2]): seq[Clip] {.inline.} =
  var timelineStart = start
  for chunk in chunkify(actionIndex, effects):
    let actionGroup = chunk[3]
    var speed = 1.0
    if actionGroup.isCut:
      speed = 99999.0
    else:
      for action in actionGroup:
        if action.kind == actSpeed:
          speed *= action.val

    let effectIndex = chunk[2]
    if effectIndex > int64(high(uint32)):
      error "'Number of actions' limit for timeline reached."
    let e = uint32(effectIndex)

    clips2.add Clip2(start: chunk[0], `end`: chunk[1], effect: e)

    if speed != 99999.0:
      let (offset, dur) = clipBounds(chunk[0], chunk[1], speed)
      if dur != 0:
        result.add Clip(src: src, start: timelineStart, dur: dur,
          offset: offset, effects: e)
        timelineStart += dur

proc initLinearTimeline*(src: ptr string, tb: AVRational, bg: RGBColor,
    mi: MediaInfo, effects: seq[Actions], actionIndex: seq[int]): v3 =
  var clips2: seq[Clip2]
  let clips = linearClips(src, effects, actionIndex, 0, clips2)

  result = v3(tb: tb, bg: bg, effects: effects, clips2: clips2, res: mi.getRes(), templateFile: src)
  mutHelper(result, mi, clips)

proc appendLinearTimeline*(tl: var v3, src: ptr string, mi: MediaInfo,
    actionIndex: seq[int]) =
  let clips = linearClips(src, tl.effects, actionIndex, tl.len, tl.clips2)

  if mi.v.len > 0:
    if tl.v.len == 0:
      tl.v.add @[]
      tl.langs.insert(mi.v[0].lang, 0)
    for clip in clips:
      var videoClip = clip
      videoClip.stream = 0
      tl.v[0].add videoClip

  var layerIdx = 0
  for i in mi.decodableAudio: # warns once per appended source
    if tl.a.len <= layerIdx:
      tl.a.add @[]
      tl.langs.add mi.a[i].lang
    for clip in clips:
      var audioClip = clip
      audioClip.stream = i.int16
      tl.a[layerIdx].add audioClip
    inc layerIdx

  for i in 0 ..< mi.s.len:
    while tl.s.len <= i:
      tl.s.add @[]
    for clip in clips:
      var subtitleClip = clip
      subtitleClip.stream = i.int16
      tl.s[i].add subtitleClip
  tl.updateNumberOfSrc()

proc mapMarkers*(tl: var v3, markers: openArray[SourceMarker]) =
  ## Place `markers`, in the inputs' frames laid end to end, on a linear
  ## `tl` through its cuts. A marker edge in a cut-out stretch moves to the
  ## next kept frame; a marker with none after it is left out.
  if markers.len == 0: return
  type Span = object
    lo, hi: int64 # the inputs' frames end to end
    inputStart: int64
    kept: bool
    clip: Clip
    map: SpeedMap
  # The chunks as linearClips turned them into clips: each input's count
  # from its own frame 0, and a kept chunk is a clip unless it rounds to
  # nothing.
  var spans: seq[Span]
  var offset, prevEnd, timelineStart = 0'i64
  for chunk in tl.clips2:
    if chunk.start == 0 and prevEnd > 0:
      offset += prevEnd
    prevEnd = chunk.`end`
    var span = Span(lo: chunk.start + offset, hi: chunk.`end` + offset,
      inputStart: offset)
    let group = tl.effects[chunk.effect]
    if not group.isCut:
      var speed = 1.0
      for a in group:
        if a.kind == actSpeed: speed *= a.val
      let (clipOffset, dur) = clipBounds(chunk.start, chunk.`end`, speed)
      if dur > 0:
        span.kept = true
        span.clip = Clip(start: timelineStart, dur: dur, offset: clipOffset,
          effects: chunk.effect)
        span.map = initSpeedMap(group)
        timelineStart += dur
    spans.add span

  # The timeline frame showing input frame `u`, or the next kept one; -1 when
  # nothing is kept from there on. `moved` tells which.
  proc place(u: int64, moved: var bool): int64 =
    for k, sp in spans:
      if u < sp.hi:
        if sp.kept and u >= sp.lo:
          let f = sp.clip.clipFrameAt(sp.map, float64(u - sp.inputStart))
          return clamp(f, sp.clip.start, sp.clip.start + sp.clip.dur - 1)
        moved = true
        for later in spans.toOpenArray(k, spans.high):
          if later.kept: return later.clip.start
        return -1
    moved = true
    -1

  let tbf = tl.tb.float64
  var movedCount, leftOut = 0
  for m in markers:
    let start = toTb(m.start, tbf).int64
    let stop = max(start, toTb(m.stop, tbf).int64)
    var moved = false
    let at = place(start, moved)
    if at < 0:
      inc leftOut
    else:
      if moved: inc movedCount
      var dur = 0'i64
      if stop > start:
        # Its end point, the frame after it: in a cut, that's the cut's place
        # on the timeline; past every kept frame, the timeline's end.
        var endMoved = false
        let endAt = place(stop, endMoved)
        dur = (if endAt >= 0: endAt else: timelineStart) - at
      tl.markers.add Marker(start: at, dur: max(0'i64, dur), name: m.name,
        note: m.note, color: m.color)
  if movedCount > 0:
    warning &"{movedCount} marker(s) in cut-out sections moved to the next kept frame"
  if leftOut > 0:
    warning &"{leftOut} marker(s) after the last kept frame left out"

proc initNonLinear(src: ptr string, tb: AVRational, mi: MediaInfo,
    clips2: seq[Clip2], effects: seq[Actions]): v3 =
  var clips: seq[Clip] = @[]
  var start: int64 = 0

  for clip2 in clips2:
    let effectGroup = effects[clip2.effect]
    if not effectGroup.isCut:
      var speed = 1.0
      for effect in effectGroup:
        if effect.kind == actSpeed:
          speed *= effect.val

      let (offset, dur) = clipBounds(clip2.start, clip2.`end`, speed)
      if dur != 0:
        clips.add(Clip(src: src, start: start, dur: dur, offset: offset,
            effects: clip2.effect))

        start += dur

  result = v3(tb: tb, effects: effects, clips2: clips2, templateFile: src)
  result.res = mi.getRes()
  mutHelper(result, mi, clips)

type EffectIndex* = object
  ## Finds an action group already in a timeline's effects by hash, where a
  ## linear search per clip is quadratic in the number of distinct groups.
  seen: int
  ids: Table[Actions, uint32]

proc intern*(index: var EffectIndex, effects: var seq[Actions],
    group: Actions): uint32 =
  ## The position in `effects` of the first group equal to `group`, which is
  ## then freed, or else of `group` itself, appended. Groups appended to
  ## `effects` some other way are picked up on the next call.
  while index.seen < effects.len:
    discard index.ids.hasKeyOrPut(effects[index.seen], uint32(index.seen))
    inc index.seen
  index.ids.withValue(group, found):
    group.free()
    return found[]
  result = uint32(effects.len)
  effects.add group
  index.ids[group] = result
  index.seen = effects.len

proc toNonLinear*(src: ptr string, tb: AVRational, mi: MediaInfo,
    chunks: seq[(int64, int64, float64)]): v3 {.raises: [AutoEditorError].} =
  var clips: seq[Clip] = @[]
  var clips2: seq[Clip2] = @[]
  var effects: seq[Actions] = @[]
  var effectIndex: EffectIndex
  var start: int64 = 0

  for chunk in chunks:
    # Check the float32 that gets stored: a tiny float64 underflows to 0.
    if chunk[2].float32 > 0.0 and chunk[2].float32 < 99999.0:
      let (offset, dur) = clipBounds(chunk[0], chunk[1], chunk[2])
      if dur != 0:
        let action =
          if chunk[2] == 1.0:
            aNil
          else:
            try: newActions([Action(kind: actSpeed, val: chunk[2].float32)])
            except ActionParseError: error "Too many actions"
        let e = effectIndex.intern(effects, action)
        clips.add Clip(src: src, start: start, dur: dur, offset: offset, effects: e)
        clips2.add Clip2(start: chunk[0], `end`: chunk[1], effect: e)
        start += dur

  result = v3(tb: tb, effects: effects, clips2: clips2, templateFile: src)
  result.res = mi.getRes()
  mutHelper(result, mi, clips)

proc toNonLinear2*(src: ptr string, tb: AVRational, mi: MediaInfo,
  clips2: seq[Clip2], effects: seq[Actions]): v3 =
  initNonLinear(src, tb, mi, clips2, effects)

proc applyArgs*(tl: var v3, args: mainArgs, audio: AudioSettings) =
  if args.sampleRate != -1:
    tl.sr = args.sampleRate
  if args.resolution[0] != 0:
    tl.res = args.resolution
  if audio.layout != "":
    tl.layout = initLayout(audio.layout)
  if args.frameRate != AVRational(num: 0, den: 0):
    tl.tb = args.frameRate
  if args.background.isSome:
    tl.bg = args.background.get()

proc validateTransitions*(tl: v3)

func transitionPlan*(clips: seq[Clip], transitions: seq[Transition]):
    seq[TransitionLink] =
  ## Match sorted edit-point transitions to sorted clips in linear time. A
  ## centered transition is outgoing for the left clip and incoming for the
  ## right clip; endpoint transitions appear on only one side.
  result = newSeq[TransitionLink](clips.len)
  var inCursor, outCursor = 0
  for i, clip in clips:
    while inCursor < transitions.len and transitions[inCursor].at < clip.start:
      inc inCursor
    if inCursor < transitions.len and transitions[inCursor].at == clip.start and
        transitions[inCursor].alignment != taEnd:
      result[i].incoming = inCursor.int32

    let clipEnd = clip.start + clip.dur
    while outCursor < transitions.len and transitions[outCursor].at < clipEnd:
      inc outCursor
    if outCursor < transitions.len and transitions[outCursor].at == clipEnd and
        transitions[outCursor].alignment != taStart:
      result[i].outgoing = outCursor.int32

func sourcedTransitions*(clips: seq[Clip], transitions: seq[Transition]):
    seq[Transition] =
  ## `transitions` without those joining a clip that has no source file, for
  ## exports that can only reference files.
  let plan = transitionPlan(clips, transitions)
  var dropped = newSeq[bool](transitions.len)
  for i, clip in clips:
    if clip.src == nil:
      for t in [plan[i].incoming, plan[i].outgoing]:
        if t >= 0: dropped[t] = true
  for i, t in transitions:
    if not dropped[i]: result.add t

proc addTransitions*(tl: var v3, kind: TransitionKind, requested: int64,
    minCut: int64 = 0) =
  ## Add start/center/end aligned transitions to primary A/V tracks: `kind` on
  ## the tracks it belongs to, a dissolve on the others. Centered transitions
  ## are shortened symmetrically so they cannot overlap a neighboring transition
  ## or consume an entire visible clip.
  if requested <= 0: return
  # `build` reads the effects, which nothing here changes; a cursor spares
  # the nested proc a copy of all of them.
  let timelineEffects {.cursor.} = tl.effects

  proc build(clips: seq[Clip], kind: TransitionKind): seq[Transition] =
    if clips.len == 0: return
    var speeds = newSeq[float64](clips.len)
    for i, clip in clips:
      speeds[i] = 1.0
      for action in timelineEffects[clip.effects]:
        if action.kind == actSpeed: speeds[i] *= action.val

    var centers: seq[Transition]
    for i in 0 ..< clips.len - 1:
      let left = clips[i]
      let right = clips[i + 1]
      if left.start + left.dur == right.start:
        let leftSpeed = speeds[i]
        let rightSpeed = speeds[i + 1]
        let leftSourceEnd = int64(round((left.offset + left.dur).float64 * leftSpeed))
        let rightSourceStart = int64(round(right.offset.float64 * rightSpeed))
        let cutDur = max(0'i64, rightSourceStart - leftSourceEnd)
        if not (left.src == right.src and cutDur < minCut):
          var half = min(requested div 2, min(left.dur, right.dur))
          # Incoming preroll is explicit in offset. For cuts within one source, the
          # removed source interval also bounds the outgoing postroll.
          half = min(half, int64(rightSourceStart.float64 / rightSpeed))
          if left.src != nil and right.src == left.src:
            half = min(half, int64(cutDur.float64 / max(leftSpeed, rightSpeed)))
          if half > 0:
            centers.add Transition(kind: kind, at: right.start,
              dur: half * 2, alignment: taCenter)

    var firstDur = min(requested, clips[0].dur)
    if centers.len > 0:
      firstDur = min(firstDur,
        centers[0].at - centers[0].dur div 2 - clips[0].start)
    if firstDur > 0:
      result.add Transition(kind: kind, at: clips[0].start,
        dur: firstDur, alignment: taStart)
    result.add centers
    let last = clips[^1]
    var lastDur = min(requested, last.dur)
    if centers.len > 0:
      let c = centers[^1]
      lastDur = min(lastDur, last.start + last.dur - (c.at + c.dur - c.dur div 2))
    if lastDur > 0:
      result.add Transition(kind: kind, at: last.start + last.dur,
        dur: lastDur, alignment: taEnd)

  let videoKind = (if kind in videoKinds: kind else: tkDissolve)
  let audioKind = (if kind in audioKinds: kind else: tkDissolve)
  tl.vt.setLen(tl.v.len)
  if tl.v.len > 0: tl.vt[0] = build(tl.v[0], videoKind)
  tl.at.setLen(tl.a.len)
  for i in 0 ..< tl.a.len: tl.at[i] = build(tl.a[i], audioKind)
  tl.validateTransitions()

proc sliceClip*(tl: var v3, index: var EffectIndex, map: SpeedMap, clip: Clip,
    lo, hi: int64): Clip =
  ## The part of `clip` from timeline frame `lo` to `hi`, which may reach past
  ## its ends. A speed ramp is cut down to the media that part covers. `map`
  ## is the clip's own, for a caller that slices it more than once.
  result = clip
  result.start = lo
  result.dur = hi - lo
  if not map.ramp:
    result.offset = clip.offset + (lo - clip.start)
    return
  if lo == clip.start and hi == clip.start + clip.dur:
    return
  let u0 = map.mediaAt(float(lo - clip.start) / clip.dur.float)
  let u1 = map.mediaAt(float(hi - clip.start) / clip.dur.float)
  # Sampled finely enough that joining the samples linearly follows any
  # easing closely.
  const n = 32
  var actions: seq[Action]
  var mean = 1.0
  for a in tl.effects[clip.effects]:
    var b = a
    if a.kind == actSpeed and a.sKf.len > 0:
      b = Action(kind: actSpeed, varispeed: a.varispeed)
      for j in 0 .. n:
        b.sKf.add float32(a.speedAt(u0 + (u1 - u0) * j.float64 / n))
      b.val = float32(b.meanSpeed)
    if b.kind == actSpeed: mean *= b.val
    actions.add b
  let media = map.mean * (clip.offset.float + clip.dur.float * u0)
  result.offset = int64(round(media / mean))
  result.effects = index.intern(tl.effects, newActions(actions))

proc sliceClip*(tl: var v3, index: var EffectIndex, clip: Clip, lo, hi: int64): Clip =
  tl.sliceClip(index, initSpeedMap(tl.effects[clip.effects]), clip, lo, hi)

func spanStart*(t: Transition): int64 =
  ## First timeline frame of the transition's span.
  t.at - (case t.alignment
    of taStart: 0'i64
    of taCenter: t.dur div 2
    of taEnd: t.dur)

proc placeTransitions*(tl: var v3, placed: seq[PlacedTransition]) =
  ## Dissolves an editor chose, at output frames it worked out from its own
  ## plan. Each is snapped to the timeline's own edit point within two frames
  ## (rounding can differ by one) and kept within its clips; one with no such
  ## point, or that would overlap the one before, is left out.
  # The nested procs would copy `placed` to capture it.
  let placed {.cursor.} = placed
  proc place(clips: seq[Clip], video: bool): seq[Transition] =
    var wanted: seq[PlacedTransition]
    for p in placed:
      if p.video == video and p.dur > 0 and p.align in 0 .. 2: wanted.add p
    wanted.sort(proc (a, b: PlacedTransition): int = cmp(a.at, b.at))
    # Clips in order and apart have their starts and ends in order too, so
    # a search finds the few within two frames instead of a scan of all.
    var ordered = true
    for i, c in clips:
      if c.dur < 0 or (i > 0 and c.start < clips[i - 1].start + clips[i - 1].dur):
        ordered = false
        break
    var priorEnd = low(int64)
    for p in wanted:
      let align = TransitionAlignment(p.align)
      var best = -1
      var bestDist = 3'i64
      var first = 0
      var last = clips.len
      if ordered:
        let atEnd = align == taEnd
        proc edgeCmp(c: Clip, key: int64): int =
          cmp((if atEnd: c.start + c.dur else: c.start), key)
        first = clips.lowerBound(p.at - 2, edgeCmp)
        last = clips.upperBound(p.at + 2, edgeCmp)
      for i in first ..< last:
        let c = clips[i]
        # Start: a clip begins here; end: one ends; center: one ends where
        # the next begins.
        let edge = case align
          of taStart: c.start
          of taEnd: c.start + c.dur
          of taCenter: c.start
        if not (align == taCenter and (i == 0 or
            clips[i - 1].start + clips[i - 1].dur != c.start)):
          if abs(edge - p.at) < bestDist:
            bestDist = abs(edge - p.at)
            best = i
      if best >= 0:
        let c = clips[best]
        let fits = p.kind in (if video: videoKinds else: audioKinds)
        var t = Transition(kind: (if fits: p.kind else: tkDissolve),
          alignment: align, dur: p.dur, easeIn: p.easeIn, easeOut: p.easeOut)
        case align
        of taStart:
          t.at = c.start
          t.dur = min(t.dur, c.dur)
        of taEnd:
          t.at = c.start + c.dur
          t.dur = min(t.dur, c.dur)
        of taCenter:
          t.at = c.start
          let room = 2 * min(c.dur, clips[best - 1].dur)
          t.dur = min(t.dur, room) div 2 * 2
        if not (t.dur <= 0 or t.spanStart < priorEnd):
          priorEnd = t.spanStart + t.dur
          result.add t

  tl.vt = newSeq[seq[Transition]](tl.v.len)
  if tl.v.len > 0: tl.vt[0] = place(tl.v[0], true)
  tl.at = newSeq[seq[Transition]](tl.a.len)
  for i in 0 ..< tl.a.len: tl.at[i] = place(tl.a[i], false)

proc validateTransitions*(tl: v3) {.raises: [].} =
  proc validateTrack(clips: seq[Clip], transitions: seq[Transition], audio: bool) =
    let kinds = (if audio: audioKinds else: videoKinds)
    var priorEnd = low(int64)
    var priorAt = low(int64)
    var leftCursor, rightCursor = 0
    for t in transitions:
      let spanStart = t.spanStart
      let spanEnd = spanStart + t.dur
      if t.dur <= 0 or spanStart < priorEnd or t.at < priorAt:
        error "Transitions must have positive, non-overlapping ranges"
      if t.kind notin kinds:
        let track = (if audio: "an audio" else: "a video")
        error &"'{t.kind}' is not {track} transition"
      while leftCursor < clips.len and
          clips[leftCursor].start + clips[leftCursor].dur < t.at:
        inc leftCursor
      while rightCursor < clips.len and clips[rightCursor].start < t.at:
        inc rightCursor
      let hasLeft = leftCursor < clips.len and
        clips[leftCursor].start + clips[leftCursor].dur == t.at
      let hasRight = rightCursor < clips.len and clips[rightCursor].start == t.at
      case t.alignment
      of taStart:
        if not hasRight: error "Start-aligned transition has no clip at its edit point"
      of taCenter:
        if not hasLeft or not hasRight:
          error "Centered transition must join adjacent clips"
      of taEnd:
        if not hasLeft: error "End-aligned transition has no clip at its edit point"
      priorEnd = spanEnd
      priorAt = t.at
  if tl.vt.len notin [0, tl.v.len] or tl.at.len notin [0, tl.a.len]:
    error "Transition track count must match media track count"
  for i in 0 ..< tl.vt.len: validateTrack(tl.v[i], tl.vt[i], false)
  for i in 0 ..< tl.at.len: validateTrack(tl.a[i], tl.at[i], true)

type RampKey = tuple[effectIdx: uint32, curve: TransitionKind, fadeIn: bool,
  dur: int64]

func fadeCurve(curve: TransitionKind, fadeIn: bool): seq[float32] =
  ## Gain across a fade, sampled finely enough that joining the samples
  ## linearly stays within half a percent of the curve.
  const n = 16
  case curve
  of tkConstantPower:
    for i in 0 .. n: result.add float32(sin(i / n * PI / 2))
  of tkExponentialFade:
    const k = 3.0
    for i in 0 .. n: result.add float32((exp(k * i.float / n) - 1) / (exp(k) - 1))
  else:
    result = @[0.0'f32, 1.0'f32]
  if not fadeIn: result.reverse()

proc withRamp(tl: var v3, cache: var Table[RampKey, uint32],
    index: var EffectIndex, effectIdx: uint32, curve: TransitionKind,
    fadeIn: bool, dur: int64): uint32 =
  let key = (effectIdx, curve, fadeIn, dur)
  if key in cache: return cache[key]
  var actions: seq[Action]
  for a in tl.effects[effectIdx]: actions.add a
  actions.add Action(kind: actVolume, kf: fadeCurve(curve, fadeIn), hasEase: true,
    easeCurve: easeLinear, easeDurUnit: duFrames, easeDur: dur.float32)
  result = index.intern(tl.effects, newActions(actions))
  cache[key] = result

proc bakeTransitions*(source: v3): v3 =
  ## Lower edit-point transitions for the native renderer to clip overlaps:
  ## audio crossfades as gain ramps, video transitions as `windows` the
  ## renderer blends. Exporters continue to consume the unmodified timeline.
  result = source.clone
  var rampCache: Table[RampKey, uint32]
  var effectIndex: EffectIndex

  proc bakeTrack(tl: var v3, track: var seq[Clip], transitions: seq[Transition],
      isVideo: bool, windows: var seq[TransitionWindow]) =
    if track.len == 0 or transitions.len == 0: return
    for t in transitions:
      if isVideo:
        windows.add TransitionWindow(start: t.spanStart, dur: t.dur,
          kind: t.kind, alignment: t.alignment, easeIn: t.easeIn,
          easeOut: t.easeOut)
    let plan = transitionPlan(track, transitions)
    let partsPerClip = (if isVideo: 1 else: 3)
    var outTrack = newSeqOfCap[Clip](track.len * partsPerClip + 2)
    for i, original in track:
      var clip = original
      var fadeInEnd = clip.start
      var fadeOutStart = 0'i64
      var hasFadeOut = false
      var inCurve, outCurve = tkDissolve

      if plan[i].incoming >= 0:
        let t = transitions[plan[i].incoming]
        let before = (if t.alignment == taCenter: t.dur div 2 else: 0'i64)
        clip.start -= before
        clip.offset = max(0'i64, clip.offset - before)
        clip.dur += before
        # A window blends the clip in by itself.
        if isVideo:
          fadeInEnd = clip.start
        else:
          fadeInEnd = clip.start + t.dur
          inCurve = t.kind

      if plan[i].outgoing >= 0:
        let t = transitions[plan[i].outgoing]
        outCurve = t.kind
        if t.alignment == taCenter:
          let after = t.dur - t.dur div 2
          clip.dur += after
          if not isVideo:
            fadeOutStart = t.at - t.dur div 2
            hasFadeOut = true
        elif not isVideo:
          fadeOutStart = t.at - t.dur
          hasFadeOut = true

      let clipEnd = clip.start + clip.dur
      fadeInEnd = min(fadeInEnd, clipEnd)
      if hasFadeOut:
        fadeOutStart = max(fadeInEnd, min(fadeOutStart, clipEnd))
      else:
        fadeOutStart = clipEnd

      # Once per clip, not per part: a ramp's map takes 512 speed lookups.
      let speedMap = initSpeedMap(tl.effects[original.effects])
      template addPart(lo, hi: int64, fadeIn, fadeOut: bool) =
        if hi > lo:
          var part = clip
          if speedMap.ramp:
            part = tl.sliceClip(effectIndex, speedMap, original, lo, hi)
          else:
            part.start = lo
            part.offset = clip.offset + (lo - clip.start)
            part.dur = hi - lo
          if fadeIn:
            part.effects = tl.withRamp(rampCache, effectIndex, part.effects,
              inCurve, true, hi - lo)
          if fadeOut:
            part.effects = tl.withRamp(rampCache, effectIndex, part.effects,
              outCurve, false, hi - lo)
          outTrack.add part

      addPart(clip.start, fadeInEnd, fadeIn = fadeInEnd > clip.start,
        fadeOut = false)
      addPart(fadeInEnd, fadeOutStart, fadeIn = false, fadeOut = false)
      addPart(fadeOutStart, clipEnd, fadeIn = false,
        fadeOut = fadeOutStart < clipEnd)
    track = outTrack

  result.windows = newSeq[seq[TransitionWindow]](result.v.len)
  for i in 0 ..< result.v.len:
    if i < result.vt.len:
      result.bakeTrack(result.v[i], result.vt[i], true, result.windows[i])
  var noWindows: seq[TransitionWindow]
  for i in 0 ..< result.a.len:
    if i < result.at.len:
      result.bakeTrack(result.a[i], result.at[i], false, noWindows)
  result.vt.setLen(0)
  result.at.setLen(0)

func stem(path: string): string =
  agSplitFile(path).name

proc setStreamTo0*(tl: var v3, interner: var StringInterner) =
  var createdDirs = initHashSet[string]()
  var cache = initTable[string, MediaInfo]()

  proc makeTrack(i: int32, path: string): MediaInfo =
    let folder: string = path.parentDir / (path.stem & "_tracks")
    if folder notin createdDirs:
      try:
        createDir(folder)
      except OSError:
        removeDir(folder)
        createDir(folder)
      createdDirs.incl folder

    let newtrack: string = folder / (path.stem & "_" & $i & ".wav")
    if newtrack notin cache:
      transcodeAudio(path, newtrack, i)
      cache[newtrack] = initMediaInfo(newtrack)
    return cache[newtrack]

  for layer in tl.a.mitems:
    for clip in layer.mitems:
      if clip.stream > 0:
        let mi = makeTrack(clip.stream, clip.src[])
        clip.src = interner.intern(mi.path)
        clip.stream = 0
  tl.updateNumberOfSrc()