Skip to content

Effort free video editing!

57.7 KB
Raw Blame
import std/[atomics, json, math, sequtils, strformat, strutils, tables]
import ../[action, av, ffmpeg, graph, log, resampler, timeline]
import ../lib/[biquad, dnorm16]
import ../util/rational
import ./convolve

# Import C string functions for JSON capture
proc strchr(s: cstring, c: cint): cstring {.importc, header: "<string.h>".}
proc strlen(s: cstring): csize_t {.importc, header: "<string.h>".}

# `va_copy` / `va_end` are macros that require lvalue access to their va_list
# argument, so they can't be imported directly when Nim passes `var VaList`
# as a pointer. Wrap them in tiny C helpers that dereference for us.
{.emit: """#include <stdarg.h>
static void nim_va_copy(va_list *dst, va_list src) { va_copy(*dst, src); }
static void nim_va_end(va_list *ap) { va_end(*ap); }
""".}
proc va_copy(dest: var VaList, src: VaList) {.importc: "nim_va_copy", nodecl.}
proc va_end(ap: var VaList) {.importc: "nim_va_end", nodecl.}

type LoudnormCapture = ref object
  buffer: array[16384, char]
  used: int

# Pointer to the currently active capture session, or nil. The C log callback
# has no user-data parameter, so we have to route through a single global, but
# the actual buffer state lives in a per-session object — concurrent or stale
# captures can't clobber each other's storage.
var activeCapture: LoudnormCapture = nil

proc loudnormLogCallbackWrapper(avcl: pointer, level: cint, fmt: ConstCString,
    vl: VaList) {.cdecl.} =
  let cap = activeCapture
  if cap == nil:
    av_log_default_callback(avcl, level, fmt, vl)
    return

  # vsnprintf consumes its VaList, so format into our local buffer using a copy
  # and leave `vl` untouched for the default callback below.
  var vlCopy: VaList
  va_copy(vlCopy, vl)
  var buffer: array[4096, char]
  discard vsnprintf(cast[cstring](addr buffer[0]), 4096, fmt, vlCopy)
  va_end(vlCopy)

  # Look for JSON content and append to the session's buffer
  let bufStr = cast[cstring](addr buffer[0])
  if strchr(bufStr, ord('{').cint) != nil and strchr(bufStr, ord('}').cint) != nil:
    let msgLen = strlen(bufStr).int
    let remaining = cap.buffer.len - cap.used - 1
    if remaining > 0 and msgLen > 0:
      let toCopy = min(msgLen, remaining)
      copyMem(addr cap.buffer[cap.used], bufStr, toCopy)
      cap.used += toCopy
      cap.buffer[cap.used] = '\0'

  av_log_default_callback(avcl, level, fmt, vl)

proc beginLoudnormCapture(): LoudnormCapture =
  if activeCapture != nil:
    error "loudnorm capture is already active"
  result = LoudnormCapture(used: 0)
  result.buffer[0] = '\0'
  activeCapture = result
  av_log_set_callback(loudnormLogCallbackWrapper)

proc endLoudnormCapture(cap: LoudnormCapture) =
  av_log_set_callback(av_log_default_callback)
  if activeCapture == cap:
    activeCapture = nil

proc getCaptured(cap: LoudnormCapture): string =
  result = newString(cap.used)
  if cap.used > 0:
    copyMem(addr result[0], addr cap.buffer[0], cap.used)

proc parseLoudnormValue(node: JsonNode, field: string): float32 =
  if node.hasKey(field):
    let value = node[field]
    if value.kind == JString:
      let strVal = value.getStr()
      if strVal == "-inf":
        return -99.0
      elif strVal == "inf":
        return 0.0
      else:
        return parseFloat(strVal).float32
    if value.kind == JFloat:
      let valNum = value.getFloat()
      if valNum == -Inf:
        return -99.0
      if valNum == Inf:
        return 0.0
      return valNum.float32
    elif value.kind == JInt:
      return value.getInt().float32
  return 0.0

type
  Getter = ref object
    container*: InputContainer
    stream*: ptr AVStream
    decoderCtx*: ptr AVCodecContext
    layout*: ref AVChannelLayout
    rate*: cint
    # Brings every decoded frame to `layout`: a stream can switch channel
    # configurations mid-way (AAC), and `get` fills a buffer sized by `layout`.
    resampler: AudioResampler
    carry: seq[int16] ## decoded past the last `get`'s end, for a sequential one

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

proc toInt16(frame: ptr AVFrame, srcStart, count: int, dst: var seq[int16],
    dstStart, dstChannels: int): bool =
  ## Frame samples [srcStart, srcStart + count) into `dst` as interleaved
  ## int16, `dstChannels` to a sample from sample `dstStart` on; channels past
  ## those are dropped. False for a sample format it doesn't read.
  let frameChannels = frame.ch_layout.nb_channels.int
  let fmt = frame.format
  let planar = fmt in [AV_SAMPLE_FMT_S16P.cint, AV_SAMPLE_FMT_S32P.cint,
    AV_SAMPLE_FMT_FLTP.cint]
  template convert(T: typedesc, sample: untyped) =
    for ch in 0 ..< min(frameChannels, dstChannels):
      let plane = (if planar: ch else: 0)
      if frame.data[plane] != nil:
        let src = frame.planeAs(plane, T)
        let (first, step) =
          if planar: (srcStart, 1)
          else: (srcStart * frameChannels + ch, frameChannels)
        for i in 0 ..< count:
          let x {.inject.} = src[first + i * step]
          dst[(dstStart + i) * dstChannels + ch] = sample
  if fmt == AV_SAMPLE_FMT_S16.cint and frameChannels == dstChannels:
    if count > 0:
      copyMem(addr dst[dstStart * dstChannels],
        addr frame.planeAs(0, int16)[srcStart * frameChannels],
        count * frameChannels * sizeof(int16))
  elif fmt in [AV_SAMPLE_FMT_S16.cint, AV_SAMPLE_FMT_S16P.cint]:
    convert(int16, x)
  elif fmt in [AV_SAMPLE_FMT_S32.cint, AV_SAMPLE_FMT_S32P.cint]:
    convert(int32, int16(ashr(x, 16)))
  elif fmt in [AV_SAMPLE_FMT_FLT.cint, AV_SAMPLE_FMT_FLTP.cint]:
    convert(cfloat, int16(max(-1.0, min(1.0, x.float64)) * 32767.0))
  elif fmt == AV_SAMPLE_FMT_DBL.cint:
    convert(cdouble, int16(max(-1.0, min(1.0, x)) * 32767.0))
  else:
    return false
  true

proc fromInt16(frame: ptr AVFrame, data: openArray[int16], channels: int) =
  ## Interleaved `data` into an S16P frame's planes, silence past its end.
  for ch in 0 ..< channels:
    let plane = frame.planeAs(ch, int16)
    for i in 0 ..< frame.nb_samples.int:
      let k = i * channels + ch
      plane[i] = (if k < data.len: data[k] else: 0)

func noteFreq(note: uint8): float = 440.0 * pow(2.0, (note.float - 69.0) / 12.0)

func toneTable(wave: Waveform, freq: float, sr: cint): seq[float32] =
  ## One cycle of a band-limited waveform, built additively: harmonics are summed
  ## only up to Nyquist, so none fold back as inharmonic aliasing the way a naive
  ## ramp or step would at high notes. Normalized to unit peak, so every timbre
  ## renders at the same level despite its own Gibbs overshoot.
  var acc = newSeq[float](toneTableLen)
  let maxK = max(1, int(sr.float / (2.0 * freq)))
  for k in 1 .. maxK:
    # saw: every harmonic at 1/k. square: odd only, 1/k. triangle: odd only,
    # 1/k^2 with alternating sign.
    let amp =
      case wave
      of wSine: (if k == 1: 1.0 else: 0.0)
      of wSaw: 1.0 / k.float
      of wSquare: (if k mod 2 == 0: 0.0 else: 1.0 / k.float)
      of wTriangle:
        if k mod 2 == 0: 0.0
        else: (if (k div 2) mod 2 == 0: 1.0 else: -1.0) / (k * k).float
    if amp != 0.0:
      for i in 0 ..< toneTableLen:
        acc[i] += amp * sin(2.0 * PI * k.float * i.float / toneTableLen.float)
  var peak = 0.0
  for v in acc:
    peak = max(peak, abs(v))
  if peak == 0.0: peak = 1.0
  result = newSeq[float32](toneTableLen)
  for i in 0 ..< toneTableLen:
    result[i] = float32(acc[i] / peak)

func synthTone(table: seq[float32], freq: float, startSample, count: int,
    channels: cint, sr: cint): seq[int16] =
  ## Play `table` at `freq`, the same on every channel. Phase is taken from the
  ## absolute output-sample index rather than carried in state, so it stays
  ## continuous across the producer's chunk boundaries and across adjacent clips
  ## holding the same note.
  let cyclesPerSample = freq / sr.float
  result = newSeq[int16](count * channels)
  for i in 0 ..< count:
    let ph = float(startSample + i) * cyclesPerSample
    let pos = (ph - floor(ph)) * toneTableLen.float
    let i0 = min(int(pos), toneTableLen - 1)
    let i1 = (if i0 + 1 == toneTableLen: 0 else: i0 + 1)
    let frac = pos - i0.float
    let v = clamp16(int32(round((table[i0].float * (1.0 - frac) +
      table[i1].float * frac) * tonePeak)))
    for ch in 0 ..< channels:
      result[i * channels + ch] = v

func toneOf(effects: Actions, act: var Action): bool =
  ## The `tone` a synthesized layer carries; false means plain silence.
  for e in effects:
    if e.kind == actTone:
      act = e
      return true

func channels(self: Getter): cint =
  self.layout.nb_channels

proc newGetter(path: string, stream: int32, rate: cint): Getter =
  result = new(Getter)
  result.container = (try: av.open(path) except IOError as e: error e.msg)
  if stream < 0 or stream >= result.container.audio.len:
    error &"{path} has no audio stream {stream}"
  result.stream = result.container.audio[stream]
  result.container.setActiveStream(result.stream.index)
  result.rate = rate
  result.decoderCtx = initDecoder(result.stream.codecpar)
  new(result.layout)
  discard av_channel_layout_copy(
    addr result.layout[], addr result.stream.codecpar.ch_layout
  )
  result.resampler = newAudioResampler(AV_SAMPLE_FMT_NONE, result.layout, 0)

proc close(getter: Getter) =
  avcodec_free_context(addr getter.decoderCtx)
  getter.container.close()

proc get(getter: Getter, start, endSample: int, sequential = false): seq[int16] =
  ## Source samples [start, endSample), interleaved. A `sequential` read
  ## carries on from where the last one stopped instead of seeking to `start`,
  ## so a long span can be taken in parts: decoding from a seek isn't exact for
  ## a lossy codec's first frames, which would mark every part's start.
  let container = getter.container
  let stream = getter.stream
  let decoderCtx = getter.decoderCtx

  let targetSamples = endSample - start
  if targetSamples <= 0:
    return @[]

  # Interleaved multi-channel; zero-filled so unwritten samples stay silent.
  result = newSeq[int16](targetSamples * getter.channels)

  # Convert sample position to time and seek
  let sampleRate = stream.codecpar.sample_rate
  let timeBase = stream.time_base
  if sampleRate <= 0 or not timeBase.isValid:
    error "Invalid stream time base or sample rate"
  let startTimeInSeconds = start.float / sampleRate.float
  let startOffset = container.startPts(stream)
  let startPts = int64(startTimeInSeconds * timeBase.den.float /
    timeBase.num.float) + startOffset

  var totalSamples = 0
  if sequential:
    let ch = getter.channels.int
    let held = min(targetSamples, getter.carry.len div ch)
    if held > 0:
      copyMem(addr result[0], addr getter.carry[0], held * ch * sizeof(int16))
      getter.carry.delete(0 ..< held * ch)
    totalSamples = held
  else:
    getter.carry.setLen(0)
    # A decoder started inside the stream needs its pre-roll before its
    # output is exact (AAC's overlap, MP3's bit reservoir), so seek that much
    # earlier; the frames before `start` are dropped below. The probe and the
    # decoder each may declare it. MP3 declares a worst case reaching
    # seconds at low MPEG-2 bitrates, more than real files use, so it's
    # capped to keep many cuts cheap.
    const maxPrerollSeconds = 1.0
    let preroll = min(max(stream.codecpar.seek_preroll, decoderCtx.seek_preroll).float /
      sampleRate.float, maxPrerollSeconds)
    let seekPts = startPts - int64(preroll * timeBase.den.float / timeBase.num.float)
    if av_seek_frame(container.formatContext, stream.index, seekPts,
        AVSEEK_FLAG_BACKWARD) < 0:
      # If seeking fails, fall back to reading from beginning
      discard av_seek_frame(container.formatContext, stream.index, 0,
        AVSEEK_FLAG_BACKWARD)

    # Flush decoder after seeking
    avcodec_flush_buffers(decoderCtx)

  var packet = av_packet_alloc()
  if packet == nil:
    error "Could not allocate packet"
  var frame = av_frame_alloc()
  if frame == nil:
    av_packet_free(addr packet)
    error "Could not allocate frame"
  defer:
    av_packet_free(addr packet)
    av_frame_free(addr frame)

  var samplesProcessed = 0

  # Shared by the demux loop and the end-of-stream decoder drain below.
  template processFrame(frame: ptr AVFrame) =
    let channels = frame.ch_layout.nb_channels
    # `result` was sized from the stream's declared layout; the getter's
    # resampler converts to it, so this only guards the copies below.
    if channels != getter.channels:
      error "Audio channel count changed mid-stream"
    let samples = frame.nb_samples

    # Convert frame PTS to sample position
    let frameSamplePos =
      if frame.pts != AV_NOPTS_VALUE:
        int64((frame.pts - startOffset).float * timeBase.num.float /
            timeBase.den.float * sampleRate.float)
      else:
        samplesProcessed.int64

    # If this frame is before our target start, skip it. A sequential read
    # is already in place, and takes every frame whole.
    if not sequential and frameSamplePos + samples.int64 <= start.int64:
      samplesProcessed += samples
    else:
      # Calculate how many samples to skip in this frame
      let samplesSkippedInFrame =
        if sequential: 0 else: max(0, start - frameSamplePos.int)
      let samplesInFrame = samples - samplesSkippedInFrame
      let samplesToProcess = min(samplesInFrame, targetSamples - totalSamples)

      if not frame.toInt16(samplesSkippedInFrame, samplesToProcess, result,
          totalSamples, channels):
        error &"Unsupported audio format: {av_get_sample_fmt_name(frame.format)}"

      let left = samplesInFrame - samplesToProcess
      if left > 0:
        let at = getter.carry.len div channels
        getter.carry.setLen((at + left) * channels)
        discard frame.toInt16(samplesSkippedInFrame + samplesToProcess, left,
          getter.carry, at, channels)

      totalSamples += samplesToProcess
      samplesProcessed += samples

  template processDecoded() =
    # Every converted frame is freed in its own pass below, after processing.
    let converted = getter.resampler.resample(frame)
    for f in converted:
      processFrame(f)
    for f in converted:
      var f = f
      av_frame_free(addr f)

  # The end is checked before each read, so that nothing is taken from the
  # demuxer or decoder and then dropped: a sequential read comes back for it.
  template drain() =
    while totalSamples < targetSamples and
        avcodec_receive_frame(decoderCtx, frame) >= 0:
      processDecoded()

  drain() # what the decoder held when the last read stopped
  while totalSamples < targetSamples and
      av_read_frame(container.formatContext, packet) >= 0:
    defer: av_packet_unref(packet)

    if packet.stream_index == stream.index:
      if avcodec_send_packet(decoderCtx, packet) >= 0:
        drain()

  # Flush the decoder: CAP_DELAY decoders may hold the tail frames.
  if totalSamples < targetSamples:
    discard avcodec_send_packet(decoderCtx, nil)
    drain()

func atempoChain(speed: float): seq[string] =
  ## atempo only behaves over a limited factor range, so a big tempo change is
  ## decomposed into a chain of smaller ones.
  const maxAtempo = 6.0
  const minAtempo = 0.5
  var rem = speed
  while rem > maxAtempo:
    result.add &"atempo={maxAtempo}"
    rem = rem / maxAtempo
  while rem < minAtempo:
    result.add &"atempo={minAtempo}"
    rem = rem / minAtempo
  if rem != 1.0:
    result.add &"atempo={rem}"

proc createFilterGraph(effects: openArray[Action], sr: cint,
    layout: ref AVChannelLayout, rampStages = 0):
  (ptr AVFilterGraph, ptr AVFilterContext, ptr AVFilterContext) =
  ## `rampStages` atempo filters named atempo@ramp0... end the chain, for a
  ## caller to change their tempo as a ramp goes.

  let filterGraph: ptr AVFilterGraph = avfilter_graph_alloc()
  if filterGraph == nil:
    error "Could not allocate audio filter graph"

  let abuffer = avfilter_get_by_name("abuffer")
  let asink = avfilter_get_by_name("abuffersink")

  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)
  if ret < 0:
    error &"Cannot create audio buffer source: {ret}"

  var bufferSink: ptr AVFilterContext = nil
  ret = avfilter_graph_create_filter(addr bufferSink, asink, nil, nil, nil, filterGraph)
  if ret < 0:
    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
  for effect in effects:
    case effect.kind
    of actSpeed:
      if at < 0: at = filters.len
      if effect.varispeed: rate *= max(0.2'f64, min(100.0'f64, effect.val))
      else: tempo *= effect.val
    of actPitch:
      if at < 0: at = filters.len
      let ratio = pow(2.0, effect.pCents.float / 1200.0)
      rate *= ratio
      tempo = tempo / ratio
    of actDeesser:
      filters.add &"deesser=i={effect.intensity}:m={effect.maxd}:f={effect.freq}"
    else: discard

  var speedFx: seq[string] = @[]
  if rate != 1.0:
    speedFx.add &"asetrate={sr}*{rate}"
    speedFx.add &"aresample={sr}" # asetrate leaves the rate changed
  speedFx.add atempoChain(tempo)
  if speedFx.len > 0:
    let i = max(at, 0)
    filters = filters[0 ..< i] & speedFx & filters[i ..< filters.len]
  for j in 0 ..< rampStages:
    filters.add &"atempo@ramp{j}=tempo=1"

  # Pin the chain's output to s16p. Some filters (e.g. deesser) emit dblp, which
  # the frame-readback in processAudioClip can't convert, yielding silence.
  let filterChain = (
    if filters.len == 0: "anull"
    else: filters.join(",") & ",aformat=sample_fmts=s16p"
  )

  var inputs = avfilter_inout_alloc()
  if inputs == nil:
    error "Could not allocate filter inputs"
  var outputs = avfilter_inout_alloc()
  if outputs == nil:
    avfilter_inout_free(addr inputs)
    error "Could not allocate filter outputs"

  outputs.name = av_strdup("in")
  outputs.filter_ctx = bufferSrc
  outputs.pad_idx = 0
  outputs.next = nil

  inputs.name = av_strdup("out")
  inputs.filter_ctx = bufferSink
  inputs.pad_idx = 0
  inputs.next = nil

  ret = avfilter_graph_parse_ptr(filterGraph, filterChain.cstring, addr inputs,
      addr outputs, nil)
  if ret < 0:
    error &"Could not parse audio filter graph: {ret}"

  ret = avfilter_graph_config(filterGraph, nil)
  if ret < 0:
    error &"Could not configure audio filter graph: {ret}"

  avfilter_inout_free(addr inputs)
  avfilter_inout_free(addr outputs)

  return (filterGraph, bufferSrc, bufferSink)

func filtersOf(act: Action, sr: float64): seq[Biquad] =
  const butterworthQ = 1.0 / sqrt(2.0)
  # Narrow enough to leave the voice between harmonics alone.
  const humQ = 30.0
  case act.kind
  of actHighpass: @[initBiquad(bqHighpass, act.cutoff.float64, butterworthQ, sr)]
  of actLowpass: @[initBiquad(bqLowpass, act.cutoff.float64, butterworthQ, sr)]
  of actDehum:
    var filters: seq[Biquad]
    for n in 1 .. act.humHarmonics.int:
      let f = act.humHz.float64 * n.float64
      if f < sr * 0.49: filters.add initBiquad(bqNotch, f, humQ, sr)
    filters
  else: @[]

proc applyVolume(data: var seq[int16], act: Action, channels: int, sr: cint,
    fps: float) =
  ## Multiply samples by the volume envelope (a static value or keyframe ramp
  ## with optional easing), following the video effects' progress rules.
  let frames = data.len div channels
  if frames == 0:
    return
  let ramp = act.ramp(act.kf, act.kt, AnimSpan(len: frames, perSec: sr.float64,
    perFrame: sr.float64 / fps))
  for i in 0 ..< frames:
    let gain = ramp.at(i)
    if gain != 1.0'f32:
      for ch in 0 ..< channels:
        let idx = i * channels + ch
        data[idx] = clamp16(int32(round(data[idx].float32 * gain)))

const rampBlock = 1024 # input samples between tempo changes in a ramp

proc runFilterChain(data: seq[int16], acts: seq[Action], sourceSr: cint,
    layout: ref AVChannelLayout, rampTempo: seq[float64] = @[]): seq[int16] =
  ## Push interleaved s16 samples through an ffmpeg filter chain built from
  ## `acts`, returning the interleaved result at the same sample rate.
  ## `rampTempo`, when given, is a tempo for each block of `rampBlock` input
  ## samples, which the chain's last stretch follows.
  let channels = layout.nb_channels
  var processedData: seq[int16]

  block:
    let samples = data.len div channels
    # atempo behaves over a limited factor range, so a ramp is spread across
    # enough stages that each stays within one.
    var stages = 0
    if rampTempo.len > 0:
      stages = 1
      for t in rampTempo:
        while pow(t, 1 / stages) > 6.0 or pow(t, 1 / stages) < 0.5: inc stages
    let (filterGraph, bufferSrc, bufferSink) = createFilterGraph(acts, sourceSr,
      layout, stages)
    defer: avfilter_graph_free(addr filterGraph)

    # Create audio frame with input data
    var inputFrame = av_frame_alloc()
    if inputFrame == nil:
      error "Could not allocate input audio frame"
    defer: av_frame_free(addr inputFrame)

    inputFrame.nb_samples = samples.cint
    inputFrame.format = AV_SAMPLE_FMT_S16P.cint
    discard av_channel_layout_copy(addr inputFrame.ch_layout, addr layout[])
    inputFrame.sample_rate = sourceSr
    inputFrame.pts = AV_NOPTS_VALUE

    if av_frame_get_buffer(inputFrame, 0) < 0:
      error "Could not allocate input audio frame buffer"

    inputFrame.fromInt16(data, channels)

    # Process through filter graph
    var outputFrames: seq[ptr AVFrame] = @[]
    defer:
      for frame in outputFrames:
        av_frame_free(addr frame)

    proc collect() =
      while true:
        var outputFrame = av_frame_alloc()
        if outputFrame == nil:
          error "Could not allocate output audio frame"
        let ret = av_buffersink_get_frame(bufferSink, outputFrame)
        if ret < 0:
          av_frame_free(addr outputFrame)
          break
        outputFrames.add(outputFrame)

    if stages == 0:
      if av_buffersrc_write_frame(bufferSrc, inputFrame) < 0:
        error "Error adding frame to audio filter"
    else:
      # Block by block, each at its tempo, so the stretch follows the ramp.
      for b, tempo in rampTempo:
        let lo = b * rampBlock
        let n = min(rampBlock, samples - lo)
        if n <= 0: break
        let arg = $pow(tempo, 1 / stages)
        for j in 0 ..< stages:
          discard avfilter_graph_send_command(filterGraph, cstring(&"atempo@ramp{j}"),
            "tempo", cstring(arg), nil, 0, 0)
        var blk = av_frame_alloc()
        blk.nb_samples = n.cint
        blk.format = AV_SAMPLE_FMT_S16P.cint
        discard av_channel_layout_copy(addr blk.ch_layout, addr layout[])
        blk.sample_rate = sourceSr
        blk.pts = lo.int64
        if av_frame_get_buffer(blk, 0) < 0:
          error "Could not allocate input audio frame buffer"
        for ch in 0 ..< channels:
          copyMem(blk.data[ch], addr inputFrame.planeAs(ch, int16)[lo],
            n * sizeof(int16))
        let ret = av_buffersrc_write_frame(bufferSrc, blk)
        av_frame_free(addr blk)
        if ret < 0:
          error "Error adding frame to audio filter"
        collect()
    if av_buffersrc_write_frame(bufferSrc, nil) < 0:
      error "Error flushing audio filter"
    collect()

    # Convert output frames back to interleaved seq[int16]
    if outputFrames.len == 0:
      processedData = @[]
    else:
      var totalSamples = 0
      for frame in outputFrames:
        totalSamples += frame.nb_samples.int

      processedData = newSeq[int16](totalSamples * channels)

      var sampleOffset = 0
      for frame in outputFrames:
        discard frame.toInt16(0, frame.nb_samples.int, processedData,
          sampleOffset, channels)
        sampleOffset += frame.nb_samples.int

  return processedData

type RateFeed = ref object
  ## Resamples interleaved samples handed over in pieces as the one stream
  ## they are, so a long span never has to be held whole.
  resampler: AudioResampler
  layout: ref AVChannelLayout
  rate: cint ## of the samples pushed
  held: seq[int16] ## resampled and not yet taken

proc newRateFeed(layout: ref AVChannelLayout, sourceSr, targetSr: cint): RateFeed =
  result = RateFeed(layout: layout, rate: sourceSr)
  result.resampler = newAudioResampler(AV_SAMPLE_FMT_S16P, layout, targetSr)

proc hold(feed: RateFeed, frames: seq[ptr AVFrame]) =
  let channels = feed.layout.nb_channels.int
  for frame in frames:
    if frame.format == AV_SAMPLE_FMT_S16P.cint:
      let at = feed.held.len div channels
      feed.held.setLen((at + frame.nb_samples.int) * channels)
      discard frame.toInt16(0, frame.nb_samples.int, feed.held, at, channels)
    var f = frame
    av_frame_free(addr f)

proc push(feed: RateFeed, data: openArray[int16]) =
  # The resampler works in floats several times the size of what it is
  # given, so hand it a little at a time.
  const pieceSamples = 1 shl 16
  let channels = feed.layout.nb_channels.int
  let samples = data.len div channels
  var at = 0
  while at < samples:
    let count = min(pieceSamples, samples - at)
    var frame = av_frame_alloc()
    if frame == nil:
      error "Could not allocate input frame for resampling"
    defer: av_frame_free(addr frame)
    frame.nb_samples = count.cint
    frame.format = AV_SAMPLE_FMT_S16P.cint
    discard av_channel_layout_copy(addr frame.ch_layout, addr feed.layout[])
    frame.sample_rate = feed.rate
    frame.pts = AV_NOPTS_VALUE
    if av_frame_get_buffer(frame, 0) < 0:
      error "Could not allocate input frame buffer for resampling"
    frame.fromInt16(data.toOpenArray(at * channels, (at + count) * channels - 1),
      channels)
    feed.hold(feed.resampler.resample(frame))
    at += count

proc finish(feed: RateFeed) =
  ## Bring out what the resampler holds back while it waits for more.
  feed.hold(feed.resampler.resample(nil))

proc take(feed: RateFeed, samples: int): seq[int16] =
  ## The next `samples` resampled, silence where they have run out.
  let channels = feed.layout.nb_channels.int
  result = newSeq[int16](samples * channels)
  let count = min(result.len, feed.held.len)
  if count > 0:
    copyMem(addr result[0], addr feed.held[0], count * sizeof(int16))
    feed.held.delete(0 ..< count)

# Returns seq[int16] where channel data is interleaved:
# [ch0, ch1, ..., ch0, ch1, ...] etc.
proc processAudioClip(ef: seq[Actions], clip: Clip, data: sink seq[int16], sourceSr,
    targetSr: cint, layout: ref AVChannelLayout, fps: float): seq[int16] =
  if data.len == 0:
    return @[]

  # Apply the clip's audio effects in their declared order, at the source
  # sample rate. Graph-backed effects (speed/varispeed/deesser) run as ffmpeg
  # filter chains; `volume` is applied per-sample in Nim so keyframe ramps and
  # easing follow the video effects' progress rules, and `convolve` in Nim since
  # the filter build has no afir. The chain is split at each of those so
  # ordering is preserved (e.g. `volume:0.5,deesser` applies the gain before the
  # deesser sees the signal).
  var processedData = data
  let channels = layout.nb_channels
  let effects = ef[clip.effects]

  # A ramp moves through the media unevenly. A varispeed ramp resamples it
  # here, its pitch following; a speed ramp's stretch follows it in the
  # filter chain. `uOf` says how far through the media each sample is.
  var hasRamp, hasVariRamp: bool
  for a in effects:
    if a.kind == actSpeed and a.sKf.len > 0:
      hasRamp = true
      if a.varispeed: hasVariRamp = true
  var uOf: seq[float32]
  if hasVariRamp:
    var rates = newSeq[float64](speedSteps + 1)
    for i in 0 .. speedSteps:
      rates[i] = 1.0
      for a in effects:
        if a.kind == actSpeed and a.varispeed and a.sKf.len > 0:
          rates[i] *= a.speedAt(i / speedSteps)
    let frames = processedData.len div channels
    var warped: seq[int16]
    var pos = 0.0
    while pos < frames.float64 - 1:
      let u = pos / frames.float64
      uOf.add float32(u)
      let i0 = int(pos)
      let f = pos - i0.float64
      for ch in 0 ..< channels:
        let a = processedData[i0 * channels + ch].float64
        let b = processedData[(i0 + 1) * channels + ch].float64
        warped.add int16(round(a + (b - a) * f))
      let r = u * speedSteps
      let k = min(int(r), speedSteps - 1)
      pos += rates[k] + (rates[k + 1] - rates[k]) * (r - k.float64)
    processedData = warped
  var rampTempo: seq[float64]
  if hasRamp and effects.anyIt(it.kind == actSpeed and not it.varispeed and
      it.sKf.len > 0):
    let frames = processedData.len div channels
    var b = 0
    while b * rampBlock < frames:
      let mid = min(frames - 1, b * rampBlock + rampBlock div 2)
      let u = (if uOf.len > 0: uOf[mid].float64 else: mid / frames)
      var tempo = 1.0
      for a in effects:
        if a.kind == actSpeed and not a.varispeed and a.sKf.len > 0:
          tempo *= a.speedAt(u)
      rampTempo.add tempo
      inc b

  var pending: seq[Action]
  template runPending() =
    if pending.len > 0:
      processedData = runFilterChain(processedData, pending, sourceSr, layout,
        rampTempo)
      rampTempo.setLen(0)
      pending.setLen(0)
  for effect in effects:
    case effect.kind
    of actSpeed:
      # A ramp is done above or by the chain's ramp stages.
      if effect.sKf.len == 0: pending.add effect
    of actDeesser, actPitch:
      pending.add effect
    of actVolume:
      runPending()
      applyVolume(processedData, effect, channels.int, sourceSr, fps)
    of actConvolve:
      runPending()
      applyConvolve(processedData, effect.irPath, channels.int, sourceSr)
    of actHighpass, actLowpass, actDehum:
      runPending()
      applyBiquads(processedData, filtersOf(effect, sourceSr.float64),
        channels.int)
    else: discard
  if rampTempo.len > 0 and pending.len == 0:
    pending.add Action(kind: actSpeed, val: 1)
  runPending()

  # Now resample from source to target sample rate
  if sourceSr == targetSr:
    # Data is already in interleaved format
    return processedData

  let feed = newRateFeed(layout, sourceSr, targetSr)
  feed.push(processedData)
  feed.finish()
  move feed.held


# Micro-fade applied at every real clip edge to kill cut pops. A splice between
# two clips is an instantaneous amplitude step (a click); ramping each edge
# to/from zero over a few ms removes the discontinuity. ~3 ms is inaudible.
const audioFadeMs = 3.0

func sourceChannel(srcCh, ch: int): int =
  ## The source channel that output channel `ch` plays, or -1 for none. A
  ## mono source is copied to the first two, the front left and right.
  if srcCh == 1: (if ch < 2: 0 else: -1)
  elif ch < srcCh: ch
  else: -1

proc mixClipPart(acc: var seq[int32], data: openArray[int16],
    duckEnv: openArray[float32], first, last, n, startSample, bufStart, accStart,
    totalSamples, fadeSamples, targetChannels, sourceChannels: int,
    fadeInEdge, fadeOutEdge: bool) =
  ## Add a clip's samples [first, last) of its `n`, which `data` holds from
  ## `first` on, to `acc`, whose first sample is the output's `accStart`.
  ## Samples before `bufStart` have been sent and are left out.
  # A clip running into the start contributes from there on.
  let lo = max(first, bufStart - startSample)
  let hi = min(min(last, totalSamples - startSample),
    first + data.len div sourceChannels)
  if hi <= lo:
    return

  template mixScaled(i: int) =
    block:
      let fadeIn = (
        if fadeInEdge and i < fadeSamples: (i.float64 + 0.5'f64) /
            fadeSamples.float64
        else: 1.0'f64
      )
      let tailDist = max(0, n - 1 - i)
      let fadeOut = (
        if fadeOutEdge and tailDist < fadeSamples: (tailDist.float64 + 0.5'f64) /
            fadeSamples.float64
        else: 1.0'f64
      )
      let gain = min(1.0'f64, min(fadeIn, fadeOut))
      let baseIndex = (startSample + i - accStart) * targetChannels
      let dg = (if duckEnv.len > 0: duckEnv[i] else: 1.0'f32)
      for ch in 0 ..< targetChannels:
        let sc = sourceChannel(sourceChannels, ch)
        if sc >= 0:
          acc[baseIndex + ch] += int32(round(data[
              (i - first) * sourceChannels + sc].float32 * gain * dg))

  if duckEnv.len > 0:
    for i in lo ..< hi:
      mixScaled(i)
    return

  # Between the fades the gain is exactly 1, so those samples skip the float
  # math, which is most of a long clip's cost.
  let a = (if fadeInEdge: max(lo, min(fadeSamples, hi)) else: lo)
  let b = (if fadeOutEdge: max(a, min(hi, n - fadeSamples)) else: hi)
  for i in lo ..< a:
    mixScaled(i)
  if sourceChannels == targetChannels:
    let dst = (startSample + a - accStart) * targetChannels
    let src = (a - first) * sourceChannels
    for k in 0 ..< (b - a) * targetChannels:
      acc[dst + k] += int32(data[src + k])
  else:
    for i in a ..< b:
      let baseIndex = (startSample + i - accStart) * targetChannels
      for ch in 0 ..< targetChannels:
        let sc = sourceChannel(sourceChannels, ch)
        if sc >= 0:
          acc[baseIndex + ch] += int32(data[(i - first) * sourceChannels + sc])
  for i in b ..< hi:
    mixScaled(i)

func clipSpeed(effs: seq[Actions], clip: Clip): float64 =
  result = 1.0
  for e in effs[clip.effects]:
    if e.kind == actSpeed:
      result *= e.val

func sameRun(effs: seq[Actions], a, b: Clip): bool =
  ## True when `b` continues `a` with no gap or jump: same source/stream/speed,
  ## adjacent in both output time and source offset. Such an edge is a mere
  ## split, not a cut, so fading across it would notch a continuous signal.
  a.src != nil and b.src != nil and a.src[] == b.src[] and a.stream == b.stream and
    a.start + a.dur == b.start and a.offset + a.dur == b.offset and
    clipSpeed(effs, a) == clipSpeed(effs, b)

func audioSampleSpan*(start, dur: int64, sampleRate: cint,
    tb: AVRational): tuple[start, dur: int] =
  ## Convert a half-open timeline interval to a half-open sample interval.
  ## Deriving the duration from absolute endpoints keeps adjacent clips
  ## contiguous when a frame contains a fractional number of audio samples.
  let sampleStart = start * sampleRate.int64 * tb.den div tb.num
  let sampleEnd = (start + dur) * sampleRate.int64 * tb.den div tb.num
  (sampleStart.int, (sampleEnd - sampleStart).int)

proc duckGainEnvelope(keyMix: seq[int32], n: int, d: Action, sr: cint,
    channels: int): seq[float32] =
  ## Per-sample gain (1.0 = open) tracking the key's peak: drop toward the
  ## floor (1 - amount) when it exceeds the threshold, smoothed by a one-pole
  ## follower whose time constant is the attack (ducking down) or release.
  result = newSeq[float32](n)
  let floorG = max(0.0'f32, 1.0'f32 - d.duckAmount.toFloat32)
  let thr = d.duckThresh.toFloat32
  let aCoef = exp(-1.0 / (sr.float * max(0.001, d.duckAttack.float / 1000.0))).float32
  let rCoef = exp(-1.0 / (sr.float * max(0.001, d.duckRelease.float /
      1000.0))).float32
  var cur = 1.0'f32
  for i in 0 ..< n:
    var peak = 0'i32
    for ch in 0 ..< channels:
      let v = abs(keyMix[i * channels + ch])
      if v > peak: peak = v
    let target = (if peak.float32 / 32768.0'f32 > thr: floorG else: 1.0'f32)
    let coef = (if target < cur: aCoef else: rCoef)
    cur = target + (cur - target) * coef
    result[i] = cur

# Wrap an interleaved int16 chunk as a planar-float (FLTP) frame for loudnorm.
proc chunkToFltpFrame(chunk: seq[int16], layout: ref AVChannelLayout, sr: cint,
    pts: var int64): ptr AVFrame =
  let channels = layout.nb_channels.int
  let nFrames = chunk.len div channels
  var frame = av_frame_alloc()
  if frame == nil:
    error "Could not allocate loudnorm input frame"
  frame.nb_samples = nFrames.cint
  frame.format = AV_SAMPLE_FMT_FLTP.cint
  discard av_channel_layout_copy(addr frame.ch_layout, addr layout[])
  frame.sample_rate = sr.cint
  frame.pts = pts
  pts += nFrames
  if av_frame_get_buffer(frame, 0) < 0:
    error "Could not allocate loudnorm input frame buffer"
  for ch in 0 ..< channels:
    let channelData = frame.planeAs(ch, cfloat)
    for i in 0 ..< nFrames:
      channelData[i] = chunk[i * channels + ch].cfloat / 32768.0'f32
  return frame

# Convert a loudnorm output frame (one of several sample formats) to an
# interleaved int16 chunk.
proc loudnormOutToChunk(outF: ptr AVFrame, channels: int): seq[int16] =
  result = newSeq[int16](outF.nb_samples.int * channels)
  if not outF.toInt16(0, outF.nb_samples.int, result, 0, channels):
    error &"Unexpected output format from loudnorm: {outF.format}"

proc makeAudioFrames*(fmt: AVSampleFormat, timeline: ptr v3, frameSize: int, layerIndices: seq[
    int], norm: Norm,
    cache: MediaCache = nil, fromSample = 0, stop: ptr Atomic[bool] = nil):
    iterator(): (ptr AVFrame, int64) =
  ## Samples from `fromSample` on (normalizing measures the whole timeline,
  ## so it needs 0). A set `stop` ends the iterator at its next call, freeing
  ## what it holds.
  # What this returns outlives the call, and capturing a timeline would copy
  # it whole. So it is borrowed, by a pointer the caller takes: the address of
  # a `v3` parameter can be that of a temporary made for the call. The caller
  # keeps the timeline alive and unmoved until done with the result.
  template tl: v3 = timeline[]

  # Paths are interned, so a path's pointer names its getter without a copy.
  var samples: Table[(ptr string, int16), Getter]
  let targetChannels = tl.layout.nb_channels
  let tb = tl.tb
  let sr = tl.sr
  let fadeSamples = max(1, int(audioFadeMs / 1000.0 * sr.float64))
  let partSamples = 10 * sr.int

  if not tb.isValid:
    error "Invalid timeline timebase"

  # Collect all unique audio sources from specified layers.
  # Audio's getter calls av_seek_frame / av_read_frame on its container, so it
  # must have an AVFormatContext that's independent of the video decoder's —
  # otherwise interleaved video+audio reads desync and the video stream emits
  # black frames after the first GOP.
  for layerIndex in layerIndices:
    if layerIndex < tl.a.len:
      for clip in tl.a[layerIndex]:
        if clip.src != nil:
          let key = (clip.src, clip.stream)
          if key notin samples:
            samples[key] = newGetter(clip.src[], clip.stream, sr)

  # A low note sums thousands of harmonics per table point, and a timeline can
  # hold hundreds of tone clips (one per kept section), so build each table once.
  var toneTables = initTable[(Waveform, uint8), seq[float32]]()

  # Calculate total duration across specified layers
  var totalDuration: int64 = 0
  for layerIndex in layerIndices:
    if layerIndex < tl.a.len:
      for clip in tl.a[layerIndex]:
        totalDuration = max(totalDuration, clip.start + clip.dur)

  let totalSamples = int(totalDuration * sr.int64 * tb.den div tb.num)

  # --- Autoducking (the `duck` action) -------------------------------------
  # A `duck` on layer L attenuates that clip by the mix of every active layer
  # with a higher index (the sidechain), so a lower layer tucks under the ones
  # beneath it. The key is mixed only over the duck clip's span (bounded memory,
  # like the normalize passes re-run the producer), with higher layers' own
  # ducks applied recursively.
  var activeLayers: seq[int]
  for li in layerIndices:
    if li < tl.a.len and tl.a[li].len > 0:
      activeLayers.add li

  # The clip's samples after its own effects, and their layout. Empty when the
  # clip has nothing to play. `durSamples` is its output span.
  proc loadClip(clip: Clip, startSample, durSamples: int):
      (seq[int16], ref AVChannelLayout) =
    let speed = clipSpeed(tl.effects, clip)
    var srcData: seq[int16]
    var srcSr = sr
    var srcLayout = tl.layout
    if clip.src == nil:
      # A source-less clip is a synthesized layer (`add:tone`) or the silent
      # base that carries one; there is no getter to read from.
      var tone: Action
      if not toneOf(tl.effects[clip.effects], tone):
        return (@[], srcLayout)
      # Match the source path's speed-scaled span, so a chained `atempo`
      # lands back on `dur` instead of leaving a gap.
      let key = (tone.wave, tone.note)
      if key notin toneTables:
        toneTables[key] = toneTable(tone.wave, noteFreq(tone.note), sr)
      srcData = synthTone(toneTables[key], noteFreq(tone.note), startSample,
        int(round(durSamples.float64 * speed)), targetChannels, sr)
    else:
      let key = (clip.src, clip.stream)
      if key notin samples:
        return (@[], srcLayout)
      let getter = samples[key]
      srcSr = getter.stream.codecpar.sample_rate
      srcLayout = getter.layout
      let sourceSr = srcSr.float64
      let sampStart = int(clip.offset.float64 * speed * sourceSr / tb)
      let sampEnd = int(float64(clip.offset + clip.dur) * speed * sourceSr / tb)
      srcData = getter.get(sampStart, sampEnd)
    (processAudioClip(tl.effects, clip, srcData, srcSr, sr, srcLayout, tb.float),
      srcLayout)

  proc mixRangeDucked(layers: seq[int], startSample, count: int): seq[int32] =
    ## Interleaved int32 mix of `layers` over output samples
    ## [startSample, startSample+count), with each clip's own duck applied.
    result = newSeq[int32](count * targetChannels)
    if count <= 0: return
    for li in layers:
      if li >= tl.a.len: continue
      for clip in tl.a[li]:
        let cStart = int(clip.start * sr.int64 * tb.den div tb.num)
        let cDur = int(clip.dur * sr.int64 * tb.den div tb.num)
        let lo = max(cStart, startSample)
        let hi = min(cStart + cDur, startSample + count)
        if hi <= lo: continue
        var duckAct: Action
        var hasDuck = false
        for e in tl.effects[clip.effects]:
          if e.kind == actDuck:
            duckAct = e
            hasDuck = true
        var (processed, srcLayout) = loadClip(clip, cStart, cDur)
        if processed.len == 0: continue
        let srcCh = srcLayout.nb_channels
        let avail = processed.len div srcCh
        if hasDuck:
          let above = activeLayers.filterIt(it > li)
          if above.len > 0:
            let n = min(avail, cDur)
            let env = duckGainEnvelope(mixRangeDucked(above, cStart, n), n, duckAct,
              sr, targetChannels)
            for local in 0 ..< n:
              let g = env[local]
              for ch in 0 ..< srcCh:
                let idx = local * srcCh + ch
                processed[idx] = clamp16(int32(round(processed[idx].float32 * g)))
        for o in lo ..< hi:
          let local = o - cStart
          if local >= avail: break
          let dst = (o - startSample) * targetChannels
          for ch in 0 ..< targetChannels:
            let sc = sourceChannel(srcCh, ch)
            if sc >= 0:
              result[dst + ch] += int32(processed[local * srcCh + sc])

  # Re-runnable streaming producer: yields the assembled, mixed, fade-applied
  # timeline as interleaved int16 chunks of up to `frameSize` sample-frames, in
  # time order, zero-padded out to `totalSamples`. Memory stays bounded by the
  # largest in-flight clip plus any cross-layer overlap — never the whole
  # timeline. Clips from every active layer are summed.
  proc newTimelineProducer(): iterator(): seq[int16] =
    return iterator(): seq[int16] =
      var cursors = newSeq[int](tl.a.len)

      var acc: seq[int32] = @[] # interleaved accumulator over [accStart, ...)
      var accStart = fromSample # output sample-frame index mapped to acc[0]
      var bufStart = fromSample # the first sample-frame not yet sent

      template startOf(li: int): int =
        int(tl.a[li][cursors[li]].start * sr.int64 * tb.den div tb.num)

      # Emit finalized sample-frames below `boundary` as `frameSize` chunks
      # (the whole remainder when `final`), then drop them from `acc`.
      template flushUpTo(boundaryArg: int, final: bool) =
        let boundary = min(boundaryArg, totalSamples)
        if (boundary - accStart) * targetChannels > acc.len:
          acc.setLen((boundary - accStart) * targetChannels)
        var emitFrames = 0
        if final:
          emitFrames = max(0, boundary - bufStart)
        else:
          while bufStart + emitFrames + frameSize <= boundary:
            emitFrames += frameSize
        var off = bufStart - accStart
        let emitEnd = off + emitFrames
        while off < emitEnd:
          let cf = min(frameSize, emitEnd - off)
          var chunk = newSeq[int16](cf * targetChannels)
          for k in 0 ..< cf * targetChannels:
            chunk[k] = clamp16(acc[off * targetChannels + k])
          off += cf
          yield chunk
        bufStart += emitFrames
        # Dropping sent samples moves all the unsent ones, which under a long
        # clip is the rest of it, so do it only once half of `acc` is spent.
        let spent = (bufStart - accStart) * targetChannels
        if spent > 0 and spent * 2 >= acc.len:
          let keep = acc.len - spent
          if keep > 0:
            moveMem(addr acc[0], addr acc[spent], keep * sizeof(int32))
          acc.setLen(keep)
          accStart = bufStart

      # Clips over before the start are never read.
      for li in activeLayers:
        while cursors[li] < tl.a[li].len:
          let c = tl.a[li][cursors[li]]
          if audioSampleSpan(c.start, c.dur, sr, tb).start +
              audioSampleSpan(c.start, c.dur, sr, tb).dur > fromSample: break
          inc cursors[li]

      while true:
        if stop != nil and stop[].load(): return
        # Pick the not-yet-processed clip with the smallest start across layers.
        var bestLi = -1
        for li in activeLayers:
          if cursors[li] < tl.a[li].len and
              (bestLi == -1 or startOf(li) < startOf(bestLi)):
            bestLi = li
        if bestLi == -1:
          break

        let clip = tl.a[bestLi][cursors[bestLi]]
        inc cursors[bestLi]

        # Only fade an edge that's a real cut; skip it when the neighbor merely
        # continues this clip (a split), so continuous audio isn't notched.
        let idx = cursors[bestLi] - 1
        let fadeInEdge = idx == 0 or
          not sameRun(tl.effects, tl.a[bestLi][idx - 1], clip)
        let fadeOutEdge = idx == tl.a[bestLi].len - 1 or
          not sameRun(tl.effects, clip, tl.a[bestLi][idx + 1])

        let effectGroup = tl.effects[clip.effects]
        let (startSample, durSamples) =
          audioSampleSpan(clip.start, clip.dur, sr, tb)

        # A long clip that plays its source as it is gets read a part at a
        # time, each mixed and emitted before the next: whole, an hour of it
        # is gigabytes. Effects work on the whole clip.
        var parts: Getter = nil
        var feed: RateFeed = nil # for a source at another rate than the output's
        var srcFrom, srcTo, srcAt = 0 # the clip's source samples, and the next to read
        var srcSr = sr
        var whole: seq[int16]
        var sourceChannels = targetChannels.int
        var n = 0 # the clip's length in output samples
        var duckEnv: seq[float32]
        if durSamples > partSamples and clip.src != nil and
            (clip.src, clip.stream) in samples and
            not effectGroup.anyIt(it.kind < actInvert):
          parts = samples[(clip.src, clip.stream)]
          srcSr = parts.stream.codecpar.sample_rate
          srcFrom = int(clip.offset.float64 * srcSr.float64 / tb)
          srcTo = max(srcFrom,
            int(float64(clip.offset + clip.dur) * srcSr.float64 / tb))
          srcAt = srcFrom
          sourceChannels = parts.channels.int
          n = min(durSamples, int((srcTo - srcFrom).int64 * sr.int64 div srcSr.int64))
          if srcSr != sr:
            feed = newRateFeed(parts.layout, srcSr, sr)
        else:
          var loaded = loadClip(clip, startSample, durSamples)
          whole = move loaded[0]
          sourceChannels = loaded[1].nb_channels.int
          n = min(durSamples, whole.len div sourceChannels)
          # Autoduck: scale this clip by the sidechain (active layers above it).
          if n > 0:
            for e in effectGroup:
              if e.kind == actDuck:
                let above = activeLayers.filterIt(it > bestLi)
                if above.len > 0:
                  duckEnv = duckGainEnvelope(
                    mixRangeDucked(above, startSample, n), n, e, sr,
                    targetChannels)
                break

        if parts != nil:
          # A clip starting under this one holds back everything after its
          # start until this one is mixed, so make room for all of that once
          # rather than a part at a time.
          var held = false
          for li in activeLayers:
            if cursors[li] < tl.a[li].len and startOf(li) < startSample + n:
              held = true
          if held and (startSample + n - accStart) * targetChannels > acc.len:
            acc.setLen((startSample + n - accStart) * targetChannels)

        var first = 0 # of the clip's samples, the next to mix
        while true:
          let last = (if parts != nil: min(n, first + partSamples) else: n)
          if parts != nil and feed == nil:
            whole = parts.get(srcFrom + first, srcFrom + last,
              sequential = first > 0)
          elif parts != nil:
            # A second of source at a time, until this part has come out.
            while feed.held.len div sourceChannels < last - first and srcAt < srcTo:
              let upTo = min(srcTo, srcAt + srcSr.int)
              feed.push(parts.get(srcAt, upTo, sequential = srcAt > srcFrom))
              srcAt = upTo
              if srcAt == srcTo:
                feed.finish()
            whole = feed.take(last - first)
          let neededFrames = startSample + last - accStart
          if neededFrames * targetChannels > acc.len:
            acc.setLen(neededFrames * targetChannels)
          mixClipPart(acc, whole, duckEnv, first, last, n, startSample, bufStart,
            accStart, totalSamples, fadeSamples, targetChannels.int, sourceChannels,
            fadeInEdge, fadeOutEdge)
          first = last

          # Everything below the next clip's start, and below what's left of
          # this one, can receive no further writes.
          var hasRemaining = first < n
          var safeBoundary = (if first < n: startSample + first else: totalSamples)
          for li in activeLayers:
            if cursors[li] < tl.a[li].len:
              hasRemaining = true
              safeBoundary = min(safeBoundary, startOf(li))
          if hasRemaining:
            flushUpTo(safeBoundary, final = false)
          if first >= n:
            break

      flushUpTo(totalSamples, final = true)

  var resampler = newAudioResampler(fmt, tl.layout, sr)
  var samplesYielded = fromSample
  var frameIndex = 0'i64

  # Wrap an interleaved int16 chunk as an S16P frame, resample to the output
  # format, and return the resulting (frame, index) pairs. Advances pts state.
  proc emitChunk(chunk: openArray[int16]): seq[(ptr AVFrame, int64)] =
    let chunkFrames = chunk.len div targetChannels
    if chunkFrames == 0:
      return @[]
    var frame = av_frame_alloc()
    if frame == nil:
      error "Could not allocate audio frame"
    defer: av_frame_free(addr frame)
    frame.nb_samples = chunkFrames.cint
    # Interleaved like the chunk, so it is one copy, and an s16 encoder
    # takes the frame as is.
    frame.format = AV_SAMPLE_FMT_S16.cint
    discard av_channel_layout_copy(addr frame.ch_layout, addr tl.layout[])
    frame.sample_rate = sr
    frame.pts = samplesYielded.int64
    frame.time_base = AVRational(num: 1, den: sr)
    if av_frame_get_buffer(frame, 0) < 0:
      error "Could not allocate audio frame buffer"
    copyMem(frame.data[0], addr chunk[0], chunkFrames * targetChannels *
      sizeof(int16))
    for newFrame in resampler.resample(frame):
      result.add (newFrame, frameIndex)
      frameIndex += 1
    samplesYielded += chunkFrames

  # EBU's loudnorm may emit a slightly different sample count than the timeline;
  # cap the apply pass to `totalSamples` so output duration is preserved.
  var ebuEmitted = 0
  proc emitCapped(chunk: openArray[int16]): seq[(ptr AVFrame, int64)] =
    if ebuEmitted >= totalSamples:
      return @[]
    let n = min(chunk.len, (totalSamples - ebuEmitted) * targetChannels)
    ebuEmitted += n div targetChannels
    return emitChunk(chunk.toOpenArray(0, n - 1))

  # loudnorm's output frames track its internal 100ms block size, not the
  # encoder's frame_size. Fixed-frame-size encoders (e.g. AAC) reject any
  # non-final frame whose sample count differs, with -22. Buffer and re-chunk
  # loudnorm output into frameSize-aligned frames before encoding.
  var rechunkBuf: seq[int16]
  proc drainRechunk(final: bool): seq[(ptr AVFrame, int64)] =
    let full = frameSize * targetChannels
    var off = 0
    while rechunkBuf.len - off >= full or (final and rechunkBuf.len > off):
      if ebuEmitted >= totalSamples:
        off = rechunkBuf.len
        break
      let take = min(full, rechunkBuf.len - off)
      for fr in emitCapped(rechunkBuf.toOpenArray(off, off + take - 1)):
        result.add fr
      off += take
    # The unsent rest moves down once, not after every piece.
    let keep = rechunkBuf.len - off
    if off > 0 and keep > 0:
      moveMem(addr rechunkBuf[0], addr rechunkBuf[off], keep * sizeof(int16))
    rechunkBuf.setLen(keep)

  return iterator(): (ptr AVFrame, int64) =
    defer:
      for getter in samples.values:
        getter.close()

    var gainLinear = 1.0'f64
    var loudnormGraph: Graph
    var fltpPts = 0'i64
    let layoutDesc = $tl.layout
    let bufferArgs = &"sample_rate={sr}:sample_fmt=fltp:channel_layout={layoutDesc}:" &
      &"time_base=1/{sr}"

    case norm.kind
    of nkNull:
      discard

    of nkPeak:
      # Pass 1: stream the timeline to find the global peak.
      var maxPeakLevel = -99.0'f32
      block:
        let produce = newTimelineProducer()
        for chunk in produce():
          for s in chunk:
            let amplitude = abs(s.float64 / 32768.0'f64)
            if amplitude > 0.0:
              let peakLevel = 20.0 * log10(amplitude)
              if peakLevel > maxPeakLevel:
                maxPeakLevel = peakLevel
      let peakAdjustment = norm.t - maxPeakLevel
      debug &"current peak level: {maxPeakLevel}"
      debug &"peak adjustment: {peakAdjustment:.3f}dB"
      if peakAdjustment != 0.0'f32:
        gainLinear = pow(10.0'f64, peakAdjustment / 20.0'f64)

    of nkEbu:
      # First pass: stream chunks through loudnorm to measure loudness.
      let capture = beginLoudnormCapture()
      let firstPass = &"i={norm.i}:lra={norm.lra}:tp={norm.tp}:offset={norm.gain}:print_format=json"
      var analysisGraph = newGraph()
      let analysisSrc = analysisGraph.add("abuffer", bufferArgs)
      let analysisFilter = analysisGraph.add("loudnorm", firstPass)
      let analysisSink = analysisGraph.add("abuffersink")
      analysisGraph.linkNodes(analysisSrc, analysisFilter, analysisSink).configure()

      block:
        let produce = newTimelineProducer()
        for chunk in produce():
          var f = chunkToFltpFrame(chunk, tl.layout, sr, fltpPts)
          analysisGraph.push(f)
          av_frame_free(addr f)
          while analysisGraph.pullTransient() != nil:
            discard
      analysisGraph.flush()
      while analysisGraph.pullTransient() != nil:
        discard
      analysisGraph.cleanup()
      endLoudnormCapture(capture)

      var measuredI = norm.i
      var measuredLRA = norm.lra
      var measuredTP = norm.tp
      var measuredThresh = -70.0'f32
      let capturedJson = capture.getCaptured()
      let jsonStart = capturedJson.find('{')
      let jsonEnd = capturedJson.rfind('}')
      if capturedJson.len > 0 and jsonStart >= 0 and jsonEnd > jsonStart:
        let jsonStr = capturedJson[jsonStart..jsonEnd]
        try:
          let jsonData = parseJson(jsonStr)
          measuredI = parseLoudnormValue(jsonData, "input_i")
          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}"
        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"
      debug &"EBU norm: {secondPass}"
      loudnormGraph = newGraph()
      let bufferSrc = loudnormGraph.add("abuffer", bufferArgs)
      let loudnormFilter = loudnormGraph.add("loudnorm", secondPass)
      let aformat = loudnormGraph.add("aformat", &"sample_rates={sr}")
      let bufferSink = loudnormGraph.add("abuffersink")
      loudnormGraph.linkNodes(bufferSrc, loudnormFilter, aformat,
          bufferSink).configure()
      fltpPts = 0

    proc pullLoudnorm() =
      while true:
        let outF = loudnormGraph.pullTransient()
        if outF == nil:
          break
        rechunkBuf.add loudnormOutToChunk(outF, targetChannels)

    # One pass over the timeline for every kind; the step after the last chunk
    # flushes loudnorm.
    let produce = newTimelineProducer()
    var done = false
    while not done:
      var frames: seq[(ptr AVFrame, int64)]
      var chunk = produce()
      if finished(produce) or (norm.kind == nkNull and stop != nil and stop[].load()):
        done = true
        if norm.kind == nkEbu:
          loudnormGraph.flush()
          pullLoudnorm()
          loudnormGraph.cleanup()
          # Pad with silence if loudnorm produced fewer samples than the timeline.
          let pending = rechunkBuf.len div targetChannels
          if ebuEmitted + pending < totalSamples:
            rechunkBuf.add newSeq[int16](
              (totalSamples - ebuEmitted - pending) * targetChannels)
          frames = drainRechunk(true)
      else:
        case norm.kind
        of nkNull:
          frames = emitChunk(chunk)
        of nkPeak:
          if gainLinear != 1.0'f64:
            for k in 0 ..< chunk.len:
              chunk[k] = int16(max(-32768.0'f64, min(32767.0'f64, chunk[k].float64 * gainLinear)))
          frames = emitChunk(chunk)
        of nkEbu:
          var f = chunkToFltpFrame(chunk, tl.layout, sr, fltpPts)
          loudnormGraph.push(f)
          av_frame_free(addr f)
          pullLoudnorm()
          frames = drainRechunk(false)
      for fr in frames:
        yield fr