Effort free video editing!
import std/[atomics, sets, strformat, strutils, tables]
from std/math import round, hypot, ceil, floor, exp, sin, cos, ln, sqrt, PI
from std/algorithm import sort, upperBound
import ../[action, av, ffmpeg, graph, log, timeline]
import ../lib/dnorm16
import ../util/[color, rational, speedmap]
import ./[burnsubs, transition]
func mod360(deg: float32): float32 {.inline.} =
# Like `floorMod(deg, 360)`, but compiles to fdiv/floor/fma instead of a
# libm `fmodf` call. Not bit-exact for huge angles; fine for rotations.
deg - 360'f32 * floor(deg / 360'f32)
type VideoFrame = object
index: int
src: ptr string
effects: Actions
local: int # frame offset within the clip, for animated effects
srcSecs: float
dur: int # clip length in frames
layer: int
win: int = -1 # the layer's transition window it is in, if any
x: float32 # overlay placement (canvas pixels, sub-pixel); 0 for the base layer
y: float32
scale: float32 # overlay size multiplier; 1.0 for the base layer
gen: bool # source-less overlay (`add:confetti`): draw on a clear canvas
fit: bool # no explicit `pos`: fit-and-center to the canvas like the base
incoming: bool # in its window, the clip coming in rather than going out
func staticRotDeg(effects: Actions): float32 =
## The clip's `rotate` angle, which `decodeClipFrame` applies.
for effect in effects:
if effect.kind == actRotate: return rotDeg(effect.rStart)
# Identity of a configured effect filter graph: everything that determines the
# graph's topology and arguments, as a flat value so the per-frame reuse check
# is a field compare instead of string formatting. Run-constants (bg color,
# graph timebase) are deliberately excluded. A tuple, for structural `==`;
# `valid` is default-false so the zero key never matches a built graph.
type GraphKey = tuple
valid: bool
kind: ActionKind
overlay: bool
w, h, fmt: cint
f0, f1, f2: float32
i0, i1, i2, i3: int32
col: uint32
type MatteKey = tuple
w, h: cint
kind: ActionKind
x, y, wd, ht, radius: int32
feather: uint8
invert: bool
polyXs, polyYs: seq[int32]
func fxId(kind: ActionKind, frame: ptr AVFrame, overlay = false,
f0 = 0'f32, f1 = 0'f32, f2 = 0'f32,
i0 = 0'i32, i1 = 0'i32, i2 = 0'i32, i3 = 0'i32, col = 0'u32): GraphKey =
(valid: true, kind: kind, overlay: overlay,
w: frame.width, h: frame.height, fmt: frame.format,
f0: f0, f1: f1, f2: f2, i0: i0, i1: i1, i2: i2, i3: i3, col: col)
func scaleTurnOf(effects: Actions): tuple[w, h, deg: float32] =
## A chain's `scale`s multiplied, across and down, and `turn`s added.
result = (1.0'f32, 1.0'f32, 0.0'f32)
for e in effects:
if e.kind == actScale:
result.w *= e.tScaleW
result.h *= e.tScaleH
elif e.kind == actTurn: result.deg += e.tDeg
func packRGB(c: RGBColor): uint32 =
uint32(c.yuv) shl 24 or uint32(c.red) shl 16 or uint32(c.green) shl 8 or uint32(c.blue)
# Effects `confine` restricts to a region (adjustment effects only; geometry
# effects like zoom/rotate/pos are intentionally left full-frame).
const confinable = {actBlur, actBrightness, actLuv, actInvert, actErosion,
actAberration, actPixelate}
func isLeft(ax, ay, bx, by, px, py: float): float =
(bx - ax) * (py - ay) - (px - ax) * (by - ay)
func polyInside(px, py: float, xs, ys: seq[int32]): bool =
var wn = 0
let n = xs.len
for i in 0 ..< n:
let (ax, ay) = (xs[i].float, ys[i].float)
let j = (i + 1) mod n
let (bx, by) = (xs[j].float, ys[j].float)
if ay <= py:
if by > py and isLeft(ax, ay, bx, by, px, py) > 0: inc wn
elif by <= py and isLeft(ax, ay, bx, by, px, py) < 0: dec wn
wn != 0
func pointSegDist(px, py, ax, ay, bx, by: float): float =
let dx = bx - ax
let dy = by - ay
let lenSq = dx * dx + dy * dy
let t = (if lenSq < 1e-9: 0.0 else: clamp(((px - ax) * dx + (py - ay) * dy) / lenSq, 0.0, 1.0))
hypot(px - (ax + t * dx), py - (ay + t * dy))
func polyEdgeDist(px, py: float, xs, ys: seq[int32]): float =
result = 1e30
let n = xs.len
for i in 0 ..< n:
let j = (i + 1) mod n
result = min(result, pointSegDist(px, py,
xs[i].float, ys[i].float, xs[j].float, ys[j].float))
proc buildPolyMaskMatte(w, h: cint, effect: Action): ptr AVFrame =
let frame = av_frame_alloc()
if frame == nil: error "Bad buffer"
frame.format = AV_PIX_FMT_GRAY8.cint
frame.width = w
frame.height = h
if av_frame_get_buffer(frame, 32) < 0: error "Bad buffer"
if av_frame_make_writable(frame) < 0: error "Can't make frame writable"
let outside = (if effect.mInvert: 255'u8 else: 0'u8)
template row(y: int): ptr UncheckedArray[uint8] = frame.planeRow(0, y)
for y in 0 ..< h.int:
let r = row(y)
for x in 0 ..< w.int: r[x] = outside
if effect.mPolyXs.len == 0:
return frame
var minX = effect.mPolyXs[0]
var maxX = minX
var minY = effect.mPolyYs[0]
var maxY = minY
for v in effect.mPolyXs:
(minX, maxX) = (min(minX, v), max(maxX, v))
for v in effect.mPolyYs:
(minY, maxY) = (min(minY, v), max(maxY, v))
let pad = effect.mFeather.int + 1
let x0 = max(0, minX.int - pad)
let x1 = min(w.int - 1, maxX.int + pad)
let y0 = max(0, minY.int - pad)
let y1 = min(h.int - 1, maxY.int + pad)
let feather = effect.mFeather.float
for y in y0 .. y1:
let r = row(y)
let fy = y.float + 0.5
for x in x0 .. x1:
let fx = x.float + 0.5
let inside = polyInside(fx, fy, effect.mPolyXs, effect.mPolyYs)
let cover =
if feather <= 0: (if inside: 1.0 else: 0.0)
else:
let d = polyEdgeDist(fx, fy, effect.mPolyXs, effect.mPolyYs)
let sdf = (if inside: -d else: d)
clamp(0.5 - sdf / feather, 0.0, 1.0)
let g = (if effect.mInvert: 255.0 * (1.0 - cover) else: 255.0 * cover)
r[x] = uint8(clamp(round(g), 0.0, 255.0))
frame
proc buildMaskMatte(w, h: cint, effect: Action): ptr AVFrame =
## A gray8 matte: white where the mask/effect applies, black elsewhere, with
## an optional `feather`-pixel soft edge; `invert` flips it. Shape from
## `mRadius`: -1 = ellipse, 0 = sharp rect, >0 = rounded-rect px.
let frame = av_frame_alloc()
if frame == nil: error "Bad buffer"
frame.format = AV_PIX_FMT_GRAY8.cint
frame.width = w
frame.height = h
if av_frame_get_buffer(frame, 32) < 0: error "Bad buffer"
let f = effect.mFeather.float
let cx = effect.mX.float + effect.mW.float / 2
let cy = effect.mY.float + effect.mH.float / 2
let hx = effect.mW.float / 2
let hy = effect.mH.float / 2
let ellipse = effect.mRadius < 0
# Feather (px) -> a normalized-radius band centered on the ellipse's edge.
let nf = f / ((hx + hy) / 2)
# r is clamped to the half-extent so corners can't over-round.
let r = min(effect.mRadius.float, min(hx, hy))
for y in 0 ..< h.int:
let row = frame.planeRow(0, y)
let dy = y.float - cy
for x in 0 ..< w.int:
let dx = x.float - cx
var cover: float # 0..1 coverage, 1 = fully inside
if ellipse:
let rr2 = (dx / hx) * (dx / hx) + (dy / hy) * (dy / hy)
cover =
if f <= 0: (if rr2 <= 1: 1.0 else: 0.0)
else: clamp(0.5 + (1 - sqrt(rr2)) / nf, 0.0, 1.0)
else:
# Rounded-box signed distance (>0 outside, 0 on edge).
let qx = abs(dx) - (hx - r)
let qy = abs(dy) - (hy - r)
let sdf = hypot(max(qx, 0), max(qy, 0)) + min(max(qx, qy), 0) - r
cover =
if f <= 0: (if sdf <= 0: 1.0 else: 0.0)
else: clamp(0.5 - sdf / f, 0.0, 1.0)
# A zero-sized shape divides by zero; its matte covers nothing.
if cover != cover: cover = 0
row[x] = uint8(round(if effect.mInvert: 255 * (1 - cover) else: 255 * cover))
frame
# Keyframe index built from AVIndexEntry for efficient seeking
type KeyframeIndex = object
frames: seq[int] # sorted list of keyframe frame numbers
avgInterval: int # average interval between keyframes (for seek decisions)
hasIndex: bool # whether the demuxer provided index entries
func videoFrameToTimestamp*(frame: int, frameRate, streamTimebase: AVRational): int64 =
## Convert a source-frame index to the stream timestamp used for seeking.
## Keep this rational: truncating the duration of one frame accumulates a
## large timestamp error in long videos (e.g. 33 ms instead of 1001/30 ms).
av_rescale_q(frame.int64, av_inv_q(frameRate), streamTimebase)
type
DecState = ref object
## One decoder reading its own demuxer. A source gets another when a
## timeline frame needs it at two places, as across a dissolve, so neither
## place makes the other seek back to a keyframe every frame.
cn: InputContainer
decoder: ptr AVCodecContext
held: ptr AVFrame # last decoded frame, held for forward reuse
deint: Graph # bwdif, from the first interlaced frame on
deintNext: ptr AVFrame # decoded at a size change, while deint drains
frameIndex: int # current source position; -1 = none yet
seekThreshold: int # don't seek-ahead before this frame
seekFrame: int # frame we seeked from, for frames-saved debug
lastSeekTarget: int # -1 = no seek performed yet
lastReqIndex: int # last obj.index requested (held-frame reuse)
loopBase: int # source frames consumed by completed loops
usedAt: int64 # timeline frame it last decoded for; -1 = never
exactFrom: int64 # stream pts; before it only reference frames decode
deintW, deintH, deintFmt: cint # what deint was built for
ownsCn: bool # opened for this decoder, not the media cache's
deintDone: bool # deint has been sent end-of-stream
interlaced: bool # has given an interlaced frame; seeks keep it
hasSeekFrame: bool # whether seekFrame holds a pending marker
SrcState = ref object
kfFrames: seq[int] # indexed keyframe frame numbers
observedKeyframes: seq[int] # keyframes any decoder saw (for backward seeks)
decoders: seq[DecState] # the first reads the media cache's container
still: ptr AVFrame # memoized decoded still; nil until first decode
frameRate: AVRational # source frames/second, also for seek timestamps
kfInterval: int # average interval between indexed keyframes
hasKfIndex: bool # whether the demuxer provided a keyframe index
isStill: bool # single-frame image source (logo/watermark)
const maxDecoders = 4 # per source; past this a busy decoder seeks instead
proc resetDeint(st: DecState) =
## Drop the deinterlacer's frames, as a seek drops the decoder's.
st.deint.cleanup()
st.deint = nil
st.deintDone = false
if st.deintNext != nil:
av_frame_free(addr st.deintNext)
type VideoSources* = ref object
## Each source's decoders, with the frame each last gave, and its decoded
## still, handed from one render to the next so a render at a frame the
## last one reached doesn't seek and decode again. A source's first decoder
## reads the media cache's container for it, so keep them together: forget
## a source here when its container leaves the cache.
srcs: Table[ptr string, SrcState]
proc free(s: SrcState) =
if s.still != nil:
av_frame_free(addr s.still)
for d in s.decoders:
if d.held != nil:
av_frame_free(addr d.held)
d.resetDeint()
avcodec_free_context(addr d.decoder)
if d.ownsCn: d.cn.close()
s.decoders.setLen(0)
proc newVideoSources*(): VideoSources = VideoSources()
proc forget*(vs: VideoSources, src: ptr string) =
## Drop what `src` holds, as when its file changes.
if src in vs.srcs:
vs.srcs[src].free()
vs.srcs.del src
proc close*(vs: VideoSources) =
for s in vs.srcs.values: s.free()
vs.srcs.clear()
proc nextFrame(st: DecState, stream: ptr AVStream, frame: ptr AVFrame): bool =
## Decode the next frame into `frame`, false at the end of the stream.
## No encoder here codes fields (VideoToolbox can't at all), and effects and
## scaling would blend the two, so interlaced pictures come out deinterlaced
## by bwdif. It needs the frame after the one it outputs, so it runs one
## frame behind the decoder; progressive sources never start it.
while true:
if st.deint != nil and st.deint.tryPull(frame):
if frame.pts != AV_NOPTS_VALUE:
frame.pts = av_rescale_q(frame.pts, st.deint.sinkTimeBase,
stream.time_base)
return true
if st.deintNext != nil:
# The old graph has given up its last frame; the new size starts fresh.
st.deint.cleanup()
st.deint = nil
av_frame_unref(frame)
av_frame_move_ref(frame, st.deintNext)
av_frame_free(addr st.deintNext)
elif st.deintDone:
return false
else:
var got = false
for _ in st.cn.flushDecode(stream.index.cint, st.decoder, frame,
st.exactFrom):
got = true
break
if not got and st.deint != nil:
# flushDecode also stops on a decode error, after which decoding
# resumes; only the decoder's own end of stream ends bwdif's.
let ret = avcodec_receive_frame(st.decoder, frame)
if ret == 0:
got = true
elif ret == AVERROR_EOF:
st.deint.flush()
st.deintDone = true
continue
if not got:
return false
if st.deint != nil and (frame.width != st.deintW or
frame.height != st.deintH or frame.format != st.deintFmt):
# A graph can't change size: drain it, then start another.
st.deintNext = av_frame_alloc()
if st.deintNext == nil:
error "Could not allocate frame"
av_frame_move_ref(st.deintNext, frame)
st.deint.flush()
continue
if st.deint == nil:
if (frame.flags and 8) == 0: # AV_FRAME_FLAG_INTERLACED
return true
let tb = stream.time_base
st.deint = newGraph()
let bsrc = st.deint.add("buffer",
&"video_size={frame.width}x{frame.height}:pix_fmt={frame.format}:" &
&"time_base={tb.num}/{tb.den}:pixel_aspect=1/1:" &
&"colorspace={frame.colorspace}:range={frame.color_range}")
let filt = st.deint.add("bwdif", "mode=send_frame:parity=auto:deint=interlaced")
let bsink = st.deint.add("buffersink")
st.deint.linkNodes(bsrc, filt, bsink).configure()
(st.deintW, st.deintH, st.deintFmt) = (frame.width, frame.height, frame.format)
st.interlaced = true
st.deint.push(frame)
proc newDecState(cn: InputContainer, decoder: ptr AVCodecContext,
ownsCn: bool): DecState =
DecState(cn: cn, ownsCn: ownsCn, decoder: decoder, frameIndex: -1,
seekThreshold: 10, lastSeekTarget: -1, lastReqIndex: -1, usedAt: -1,
exactFrom: AV_NOPTS_VALUE)
proc buildKeyframeIndex(stream: ptr AVStream, fps: float,
defaultInterval: int): KeyframeIndex =
## Build a keyframe index from the stream's index entries.
result.frames = @[]
result.hasIndex = false
result.avgInterval = defaultInterval
let count = avformat_index_get_entries_count(stream)
if count <= 0:
return
result.hasIndex = true
let tb = stream.time_base
let reorderDelay = max(stream.codecpar.video_delay.int, 0)
for i in 0 ..< count:
let entry = avformat_index_get_entry(stream, i)
if entry != nil and entry.isKeyframe and entry.timestamp != AV_NOPTS_VALUE:
let frameNum = int(round(
float(entry.timestamp) * float(tb.num) / float(tb.den) * fps))
# Be a bit conservative by adding video_delay (the worst-case DTS/PTS gap), even
# if some formats use PTS.
result.frames.add(max(frameNum + reorderDelay, 0))
if result.frames.len >= 2:
var total = 0
for i in 1 ..< result.frames.len:
total += result.frames[i] - result.frames[i - 1]
result.avgInterval = total div (result.frames.len - 1)
func toInt(r: AVRational): int =
(r.num div r.den).int
proc newSwsCtx(): ptr SwsContext =
result = sws_alloc_context()
if result == nil:
error "Failed to allocate sws context"
# sws_alloc_context defaults to a single thread.
result.setOpt("threads", 0)
proc reformat*(frame: ptr AVFrame, format: AVPixelFormat, width: cint = 0,
height: cint = 0, ctx: ptr SwsContext = nil): ptr AVFrame =
if frame == nil:
return nil
let srcFormat = AVPixelFormat(frame.format)
let srcWidth = frame.width
let srcHeight = frame.height
let dstWidth = if width > 0: width else: srcWidth
let dstHeight = if height > 0: height else: srcHeight
if srcFormat == format and srcWidth == dstWidth and srcHeight == dstHeight:
return frame
let newFrame = av_frame_alloc()
if newFrame == nil:
error "Failed to allocate new frame"
newFrame.format = format.cint
newFrame.width = dstWidth
newFrame.height = dstHeight
newFrame.pts = frame.pts
newFrame.time_base = frame.time_base
newFrame.flags = frame.flags and (8 or 16).cint
newFrame.color_primaries = frame.color_primaries
newFrame.color_trc = frame.color_trc
if srcFormat.isRgb == format.isRgb:
newFrame.color_range = frame.color_range
newFrame.colorspace = frame.colorspace
elif format.isRgb or frame.colorspace in [0, 2]:
# The matrix and range don't carry between RGB and YUV. An RGB source's
# AVCOL_SPC_RGB tag on a YUV frame makes swscale copy the channels into
# Y/U/V unconverted, a strong green/purple shift (#1289). Leave them
# unspecified so swscale uses its defaults.
newFrame.color_range = 0 # AVCOL_RANGE_UNSPECIFIED
newFrame.colorspace = if format.isRgb: 0 else: 2 # AVCOL_SPC_RGB / UNSPECIFIED
else:
# An RGB frame tagged with a YUV matrix came from a decoder that did the
# YUV to RGB step itself (a browser VideoDecoder); converting back with
# the same matrix and range restores the stream's samples.
newFrame.color_range = frame.color_range
newFrame.colorspace = frame.colorspace
var ret = av_frame_get_buffer(newFrame, 32)
if ret < 0:
error &"Failed to allocate buffer for new frame: {ret}"
var ownedCtx: ptr SwsContext = nil
let swsCtx =
if ctx != nil: ctx
else:
ownedCtx = newSwsCtx()
ownedCtx
ret = sws_scale_frame(swsCtx, newFrame, frame)
if ownedCtx != nil:
sws_free_context(addr ownedCtx)
if ret < 0:
error "Failed to scale frame"
return newFrame
proc toImg(frame: ptr AVFrame, ctx: ptr SwsContext): Img =
let rgb = frame.reformat(AV_PIX_FMT_RGB24, ctx = ctx)
result = Img(w: rgb.width.int, h: rgb.height.int)
result.px = newSeq[uint8](result.w * result.h * 3)
for y in 0 ..< result.h:
copyMem(addr result.px[y * result.w * 3],
cast[pointer](cast[int](rgb.data[0]) + y * rgb.linesize[0].int), result.w * 3)
if rgb != frame:
var f = rgb
av_frame_free(addr f)
proc fromImg(im: Img, like: ptr AVFrame, ctx: ptr SwsContext): ptr AVFrame =
## `im` in the format and color tags of `like`, so the round trip through
## RGB uses the same matrix both ways.
var rgb = av_frame_alloc()
if rgb == nil: error "Could not allocate a transition frame"
rgb.format = AV_PIX_FMT_RGB24.cint
rgb.width = im.w.cint
rgb.height = im.h.cint
rgb.color_primaries = like.color_primaries
rgb.color_trc = like.color_trc
if av_frame_get_buffer(rgb, 32) < 0: error "Could not allocate a transition frame"
for y in 0 ..< im.h:
copyMem(cast[pointer](cast[int](rgb.data[0]) + y * rgb.linesize[0].int),
addr im.px[y * im.w * 3], im.w * 3)
if AVPixelFormat(like.format).isRgb:
rgb.colorspace = like.colorspace
rgb.color_range = like.color_range
else:
rgb.colorspace = 0 # AVCOL_SPC_RGB
result = av_frame_alloc()
if result == nil: error "Could not allocate a transition frame"
result.format = like.format
result.width = like.width
result.height = like.height
result.colorspace = like.colorspace
result.color_range = like.color_range
result.color_primaries = like.color_primaries
result.color_trc = like.color_trc
if av_frame_get_buffer(result, 32) < 0: error "Could not allocate a transition frame"
let ret = sws_scale_frame(ctx, result, rgb)
av_frame_free(addr rgb)
if ret < 0: error "Failed to convert a transition frame"
func zoomSpan(n, scaled, step: cint): tuple[start, len, scaledLen: cint, offset: float] =
## Along one axis of length `n` zoomed to `scaled`: the `step`-aligned source
## span covering the centered `n` output pixels, its length once scaled, and
## where those pixels start in it. The span gets a margin so the scaler's
## taps at the edges read real pixels.
let ratio = float(n) / float(scaled)
let ox = float(scaled - n) / 2
let first = max(0, cint(floor(ox * ratio)) - 2) div step * step
let last = min(n, (cint(ceil((ox + float(n)) * ratio)) + 2 + step - 1) div step * step)
let scaledLen = max(n, cint(round(float(last - first) / ratio)))
(first, last - first, scaledLen, ox - float(first) / ratio)
type YuvTag = tuple[space, range: cint]
const untagged: YuvTag = (2.cint, 0.cint)
func tagOf(frame: ptr AVFrame): YuvTag {.inline.} = (frame.colorspace, frame.color_range)
func toYuv(color: RGBColor, tag: YuvTag): tuple[y, u, v: uint8] =
## RGB -> YUV in `tag`'s matrix and range, shared by every solid-color write
## into a planar frame.
if color.yuv:
return (color.red, color.green, color.blue)
let (y, cb, cr) = rgbToYuv(color.red.float / 255, color.green.float / 255,
color.blue.float / 255, yuvMatrix(tag.space.int), tag.range == 2)
func code(v: float): uint8 = uint8(clamp(round(v), 0.0, 255.0))
(code(y), code(cb), code(cr))
proc makeClear(width: cint, height: cint): ptr AVFrame =
## A transparent RGBA canvas: the starting picture for a generator layer
## (`add:confetti`), so only what it draws survives the composite.
let frame: ptr AVFrame = av_frame_alloc()
if frame == nil:
return nil
frame.format = AV_PIX_FMT_RGBA.cint
frame.width = width
frame.height = height
if av_frame_get_buffer(frame, 32) < 0:
error "Bad buffer"
if av_frame_make_writable(frame) < 0:
error "Can't make frame writable"
for y in 0 ..< height:
zeroMem(cast[pointer](cast[int](frame.data[0]) + y.int * frame.linesize[0].int),
width.int * 4)
return frame
proc fillBox(frame: ptr AVFrame, x, y, w, h: int32, color: RGBColor) =
let (yv, uv, vv) = toYuv(color, frame.tagOf)
let x0 = clamp(x.int, 0, frame.width.int)
let y0 = clamp(y.int, 0, frame.height.int)
let x1 = clamp(x.int + w.int, 0, frame.width.int)
let y1 = clamp(y.int + h.int, 0, frame.height.int)
if x0 >= x1 or y0 >= y1:
return
for y in y0 ..< y1:
let p = frame.planeRow(0, y)
for col in x0 ..< x1:
p[col] = yv
for y in (y0 div 2) .. ((y1 - 1) div 2):
let u = frame.planeRow(1, y)
let v = frame.planeRow(2, y)
for col in (x0 div 2) .. ((x1 - 1) div 2):
u[col] = uv
v[col] = vv
func lutOf(scale, offset: float32): array[256, uint8] =
## lutrgb's table for `val*scale+offset`. Both numbers go through their
## decimal text, as they do in that filter's expression, so a render matches
## an editor export that carries the expression.
let s = parseFloat(&"{scale}")
let o = parseFloat(&"{offset}")
for v in 0 .. 255:
result[v] = uint8(clamp(int(v.float * s + o), 0, 255))
proc applyLut(frame: ptr AVFrame, lut: array[256, uint8], first, step, pixel: int) =
## Map each `step`th byte of a packed frame's rows through `lut`, starting
## at byte `first`; `pixel` is the bytes per pixel.
# A frame out of a graph can share its buffer with the decode cache.
if av_frame_make_writable(frame) < 0:
error "Could not make frame writable for a lookup table"
let rowLen = frame.width.int * pixel
for y in 0 ..< frame.height.int:
let row = frame.planeRow(0, y)
var x = first
while x < rowLen:
row[x] = lut[row[x]]
x += step
proc memset(p: pointer, c: cint, n: csize_t): pointer {.importc,
header: "<string.h>", discardable.}
proc makeSolid(width: cint, height: cint, color: RGBColor,
tag = untagged): ptr AVFrame =
let frame: ptr AVFrame = av_frame_alloc()
if frame == nil:
return nil
frame.format = AV_PIX_FMT_YUV420P.cint
frame.width = width
frame.height = height
frame.colorspace = tag.space
frame.color_range = tag.range
if av_frame_get_buffer(frame, 32) < 0:
error "Bad buffer"
if av_frame_make_writable(frame) < 0:
error "Can't make frame writable"
let (yValue, uValue, vValue) = toYuv(color, tag)
let yData: ptr uint8 = frame.data[0]
let yLinesize: cint = frame.linesize[0]
for y in 0 ..< height:
memset(cast[pointer](cast[int](yData) + y.int * yLinesize.int),
yValue.cint, csize_t(width))
let uData: ptr uint8 = frame.data[1]
let uLinesize: cint = frame.linesize[1]
for y in 0 ..< (height div 2):
memset(cast[pointer](cast[int](uData) + y.int * uLinesize.int),
uValue.cint, csize_t((width div 2)))
let vData: ptr uint8 = frame.data[2]
let vLinesize: cint = frame.linesize[2]
for y in 0 ..< (height div 2):
memset(cast[pointer](cast[int](vData) + y.int * vLinesize.int),
vValue.cint, csize_t((width div 2)))
return frame
# Indexed by ConfettiScheme, so the rows must stay in enum order.
const confettiPalettes: array[ConfettiScheme, seq[uint32]] = [
@[0xff0040'u32, 0xff7a00'u32, 0xffe000'u32, 0x00e04b'u32, 0x0091ff'u32, 0xc800ff'u32],
@[0x00fff0'u32, 0xff00d4'u32, 0xb6ff00'u32, 0xff7a00'u32, 0x9d00ff'u32],
@[0xffd700'u32, 0xffb300'u32, 0xe0a63c'u32],
@[0xff3366'u32, 0x33ccff'u32],
@[0xffffff'u32],
]
func unpackRGB(v: uint32): RGBColor =
RGBColor(red: uint8((v shr 16) and 0xff), green: uint8((v shr 8) and 0xff),
blue: uint8(v and 0xff))
func towardWhite(c: RGBColor, t: float32): RGBColor =
## Mix `c` toward white by `t` in [0, 1].
let f = clamp(t, 0.0'f32, 1.0'f32)
template mix(v: uint8): uint8 =
uint8(float32(v) + (255.0'f32 - float32(v)) * f)
RGBColor(red: mix(c.red), green: mix(c.green), blue: mix(c.blue))
func hashUnit(i, salt: uint32): float32 =
## A value in [0, 1) for piece `i`, channel `salt`. A hash, not an RNG: no
## state to seed, and two renders of one command match.
var h = i * 0x9E3779B1'u32 + salt * 0x85EBCA6B'u32 + 0x165667B1'u32
h = (h xor (h shr 16)) * 0x7FEB352D'u32
h = (h xor (h shr 15)) * 0x846CA68B'u32
h = h xor (h shr 16)
float32(h shr 8) / 16777216.0'f32
func launchFor(rise, k, vt: float32): float32 =
## Upward speed that peaks `rise` frame-heights above the start. Inverts
## `rise = (u - vt*ln(1 + u/vt)) / k`, which has no closed form: as x = u/vt it
## is `x - ln(1+x) = a`, seeded from its two limits and polished with Newton.
if vt <= 1e-4'f32:
return k * rise # no gravity: the piece just coasts to a stop, at u/k
let a = k * rise / vt
var x = a + sqrt(2.0'f32 * a)
for _ in 0 ..< 2:
x -= (x - ln(1.0'f32 + x) - a) * (1.0'f32 + x) / x
vt * x
const tau = 6.2831855'f32
type Chip = array[4, tuple[x, y: float32]] # a piece's four corners
func chipOutline(n: uint32, rx, ry: float32, v: var Chip) =
## The piece's flat shape: a quad cut irregularly, so the burst is not a
## screenful of identical rectangles. Corners stay in their own quadrant, which
## keeps the outline convex for fillChip.
const cx = [-1.0'f32, 1.0'f32, 1.0'f32, -1.0'f32]
const cy = [-1.0'f32, -1.0'f32, 1.0'f32, 1.0'f32]
for j in 0 ..< 4:
let u = uint32(j)
v[j] = (cx[j] * rx * (0.55'f32 + 0.45'f32 * hashUnit(n, 20 + u)),
cy[j] * ry * (0.55'f32 + 0.45'f32 * hashUnit(n, 24 + u)))
type Cov = array[512, float32]
## Per-row coverage scratch. A chip spans at most ~0.05 of the frame height, so
## this holds one up to a ~10k-tall frame; wider than that just clips.
func chipArea(poly: Chip): float32 =
var a = 0.0'f32
for j in 0 ..< 4:
let b = poly[(j + 1) and 3]
a += poly[j].x * b.y - b.x * poly[j].y
abs(a) * 0.5'f32
func addSpan(poly: Chip, yc: float32, x0, n: int, weight: float32,
cov: var Cov) =
## Add `weight` times the polygon's horizontal coverage at height `yc` into
## `cov`, indexed from pixel `x0`. Exact in x: a pixel the span crosses partway
## takes only that fraction, which is what softens the left and right edges.
var lo = 1e30'f32
var hi = -1e30'f32
for j in 0 ..< 4:
let a = poly[j]
let b = poly[(j + 1) and 3]
# A horizontal edge fails at both ends, so the slope cannot divide by 0.
if (a.y <= yc) != (b.y <= yc):
let x = a.x + (yc - a.y) * (b.x - a.x) / (b.y - a.y)
lo = min(lo, x)
hi = max(hi, x)
if lo >= hi:
return
for k in max(int(floor(lo)) - x0, 0) ..< min(int(ceil(hi)) - x0, n):
let px = float32(x0 + k)
let overlap = min(hi, px + 1.0'f32) - max(lo, px)
if overlap > 0.0'f32:
cov[k] += weight * overlap
proc fillChip(frame: ptr AVFrame, poly: Chip, color: RGBColor) =
## Draw the projected outline, blended by how much of each pixel it covers.
## Coverage comes from four sub-scanlines a row, each measured exactly in x, so
## both the sloped edges and the ends of a turning chip come out smooth.
var xMin, xMax = poly[0].x
var yMin, yMax = poly[0].y
for j in 1 ..< 4:
xMin = min(xMin, poly[j].x)
xMax = max(xMax, poly[j].x)
yMin = min(yMin, poly[j].y)
yMax = max(yMax, poly[j].y)
let x0 = max(int(floor(xMin)), 0)
let y0 = max(int(floor(yMin)), 0)
let x1 = min(int(ceil(xMax)) + 1, frame.width.int)
let y1 = min(int(ceil(yMax)) + 1, frame.height.int)
if x0 >= x1 or y0 >= y1:
return
let n = min(x1 - x0, 512)
# Turned nearly edge-on, so it is thinner than the sub-scanline spacing and
# sampling can miss it outright. Lay its area over the footprint, so a sliver
# dims as it turns.
let flat = xMax - xMin < 1.0'f32 or yMax - yMin < 1.0'f32
let flatCov =
if flat: clamp(chipArea(poly) / float32(n * (y1 - y0)), 0.0'f32, 1.0'f32)
else: 0.0'f32
let rgba = AVPixelFormat(frame.format) == AV_PIX_FMT_RGBA
let (yv, uv, vv) = toYuv(color, frame.tagOf)
var cov: array[2, Cov]
# Paired luma rows, because both share one chroma row and it must only be
# blended once.
for cy in (y0 div 2) .. ((y1 - 1) div 2):
var hit = false
for half in 0 .. 1:
let y = cy * 2 + half
for k in 0 ..< n:
cov[half][k] = 0.0'f32
if y < y0 or y >= y1:
continue
if flat:
for k in 0 ..< n:
cov[half][k] = flatCov
hit = flatCov > 0.0'f32
else:
for sub in 0 ..< 4:
addSpan(poly, float32(y) + (float32(sub) + 0.5'f32) * 0.25'f32,
x0, n, 0.25'f32, cov[half])
let row = frame.planeRow(0, y)
for k in 0 ..< n:
let c = cov[half][k]
if c <= 0.002'f32:
continue
hit = true
let x = x0 + k
if rgba:
# Non-premultiplied source-over, so pieces layered on the clear canvas
# of a generator layer keep a correct alpha.
let dstA = float32(row[x * 4 + 3]) / 255.0'f32
let outA = dstA + (1.0'f32 - dstA) * c
if outA <= 0.0'f32:
continue
for ch, src in [color.red, color.green, color.blue]:
let dst = float32(row[x * 4 + ch])
row[x * 4 + ch] = uint8((float32(src) * c +
dst * dstA * (1.0'f32 - c)) / outA + 0.5'f32)
row[x * 4 + 3] = uint8(outA * 255.0'f32 + 0.5'f32)
else:
row[x] = uint8(float32(row[x]) * (1.0'f32 - c) +
float32(yv) * c + 0.5'f32)
if not rgba and hit:
# Chroma is half resolution, so one sample stands for a 2x2 luma block. Take
# the block's strongest coverage, or a thin sliver would lose its color.
let uRow = frame.planeRow(1, cy)
let vRow = frame.planeRow(2, cy)
for cx in (x0 div 2) .. ((x1 - 1) div 2):
var c = 0.0'f32
for k in (cx * 2 - x0) .. (cx * 2 + 1 - x0):
if k >= 0 and k < n:
c = max(c, max(cov[0][k], cov[1][k]))
if c <= 0.002'f32:
continue
uRow[cx] = uint8(float32(uRow[cx]) * (1.0'f32 - c) + float32(uv) * c + 0.5'f32)
vRow[cx] = uint8(float32(vRow[cx]) * (1.0'f32 - c) + float32(vv) * c + 0.5'f32)
proc drawConfetti(frame: ptr AVFrame, act: Action, local: int, fps: float) =
## One frame of the confetti animation.
##
## Linear-drag ballistics: v(t) = vt + (v0 - vt)e^-kt for terminal velocity
## vt = g/k, so a piece arcs over and settles into a drift rather than
## accelerating off-screen. Lengths and speeds are fractions of the frame
## height, so the look is resolution-independent.
let w = frame.width.float32
let h = frame.height.float32
let palette = confettiPalettes[act.cScheme]
let t0 = float32(local) / float32(max(fps, 1.0))
for i in 0 ..< act.cCount.int:
let n = uint32(i) + uint32(act.cSeed) * 7919'u32
let uPos = hashUnit(n, 1)
let uSpeed = hashUnit(n, 2)
let uAim = hashUnit(n, 3)
let uSize = hashUnit(n, 4)
let uSway = hashUnit(n, 5)
let uSpin = hashUnit(n, 6)
let uWhen = hashUnit(n, 7)
let uShape = hashUnit(n, 9)
let uTumble = hashUnit(n, 10)
let uPhase = hashUnit(n, 11)
let uRoll = hashUnit(n, 12)
# Air resistance, 1/s, per piece: spread wide so the burst fans into a
# ragged front instead of falling as one sheet.
let k = 1.6'f32 + 3.2'f32 * hashUnit(n, 13)
# Equal shove for all, so draggier pieces leave faster and brake sooner.
let shove = 0.55'f32 + 0.45'f32 * (k / 3.2'f32)
let vt = act.cGravity / k # terminal fall speed, frame-heights/s
# Apex as a fraction of the climb to just past the top edge. Solving the
# throw from this keeps the height independent of gravity; squaring it piles
# the burst low, so only the strongest pieces clear the frame.
const overTop = 0.03'f32
let reach = 0.52'f32 + 0.48'f32 * uSpeed * uSpeed
var x0, y0, vx0, vy0: float32
case act.cOrigin
of coBottom:
x0 = w * (0.02'f32 + 0.96'f32 * uPos)
y0 = h * 1.02'f32
vy0 = -launchFor(reach * (1.02'f32 + overTop), k, vt)
vx0 = (uAim * 2.0'f32 - 1.0'f32) * 0.7'f32
of coSides:
# A wide fan, down to almost no sideways push, so some pieces climb and
# fall along the edge instead of the sides emptying out.
let right = (i mod 2) == 1
let top = 0.90'f32 + 0.14'f32 * uPos
x0 = (if right: w * 1.02'f32 else: w * -0.02'f32)
y0 = h * top
vy0 = -launchFor(reach * (top + overTop), k, vt)
vx0 = (0.15'f32 + 3.0'f32 * uAim) * (if right: -1.0'f32 else: 1.0'f32)
of coCenter:
# Radial: the reach is measured against the piece thrown straight up.
x0 = w * 0.5'f32
y0 = h * 0.5'f32
let angle = uPos * tau
let speed = launchFor(reach * (0.5'f32 + overTop), k, vt)
vx0 = cos(angle) * speed
vy0 = sin(angle) * speed
of coTop:
x0 = w * (0.02'f32 + 0.96'f32 * uPos)
y0 = h * -0.06'f32
vy0 = (0.6'f32 + 0.5'f32 * uSpeed) * shove # a release, not a throw
vx0 = (uAim * 2.0'f32 - 1.0'f32) * 0.15'f32
# Sideways only: scaling the climb would undo launchFor's fixed apex.
vx0 *= shove
# Fired once per section, nothing replaced after it falls out. The stagger is
# short against the whole burst, so it rips out but still reads as one pop.
let t = t0 - uWhen * 0.4'f32
if t > 0.0'f32:
let decay = (1.0'f32 - exp(-k * t)) / k
let sway = h * (0.010'f32 + 0.020'f32 * uSway)
let freq = 0.5'f32 + uSpin
let px = x0 + vx0 * decay * h + sway * sin(tau * freq * t + uSway * tau)
let py = y0 + (vt * t + (vy0 - vt) * decay) * h
let size = h * (0.024'f32 + 0.024'f32 * uSize)
# Phrased positively so a non-finite piece is dropped rather than reaching
# an unchecked float -> int conversion. `size` bounds the outline.
if px + size >= 0.0'f32 and px - size <= w and
py + size >= 0.0'f32 and py - size <= h:
# Spin in-plane (Rz) while tumbling end over end (Rx) and edge to edge (Ry).
# The chip is flat, so local z = 0 collapses the three matrices to this;
# dropping z projects it, foreshortening a chip that turns away.
let spinZ = (1.5'f32 + 4.0'f32 * uSpin) * t + uPhase * tau
let turnX = (2.0'f32 + 5.0'f32 * uTumble) * t + uSize * tau
let turnY = (1.5'f32 + 4.0'f32 * uRoll) * t + uAim * tau
let ca = cos(spinZ)
let sa = sin(spinZ)
let cb = cos(turnX)
let sb = sin(turnX)
let cc = cos(turnY)
let sc = sin(turnY)
var poly: Chip # uShape sets the proportions: narrow strip to near-square
chipOutline(n, size * 0.5'f32, size * (0.22'f32 + 0.28'f32 * uShape), poly)
for j in 0 ..< 4:
let lx = poly[j].x * ca - poly[j].y * sa
let ly = poly[j].x * sa + poly[j].y * ca
poly[j] = (px + lx * cc + ly * sb * sc, py + ly * cb)
let idx = min(palette.len - 1, int(hashUnit(n, 8) * float32(palette.len)))
var color = unpackRGB(palette[idx])
if act.cShimmer:
# cb*cc is how square-on the chip is to the viewer, so near 0 is edge-on:
# the angle that catches a light off to the side. Ramped, so the glint
# rolls through the turn.
const glintBelow = 0.25'f32
let facing = abs(cb * cc)
if facing < glintBelow:
color = towardWhite(color, (glintBelow - facing) / glintBelow)
fillChip(frame, poly, color)
proc scaleWithPad(src: ptr AVFrame, targetW, targetH: int32,
bg: RGBColor, tag: YuvTag, swsCtx: var ptr SwsContext): ptr AVFrame =
## Scale src to fit within targetW x targetH preserving aspect ratio,
## centering with bg color padding. Returns a new YUV420P frame.
## Uses sws_scale_frame rather than a filter graph to avoid NEON crashes
## on Windows ARM64.
let srcW = src.width
let srcH = src.height
# Compute fitted dims (equivalent to scale=force_original_aspect_ratio=decrease)
var scaledW = targetW
var scaledH = targetH
if srcW.int * targetH.int > srcH.int * targetW.int:
scaledH = cint((srcH.int * targetW.int) div srcW.int) and not 1.cint
if scaledH < 2: scaledH = 2
elif srcH.int * targetW.int > srcW.int * targetH.int:
scaledW = cint((srcW.int * targetH.int) div srcH.int) and not 1.cint
if scaledW < 2: scaledW = 2
var output = makeSolid(targetW, targetH, bg, tag)
if output == nil:
error "Could not create background frame in scaleWithPad"
output.pts = src.pts
output.time_base = src.time_base
# Even pixel offsets required for YUV420P chroma subsampling
let ox = ((targetW - scaledW) div 2) and not 1.cint
let oy = ((targetH - scaledH) div 2) and not 1.cint
# Scale straight into the centered region: planes that point into `output`
# are buffers sws_scale_frame fills as given, and owning none, the view
# frees nothing of them.
var view = av_frame_alloc()
if view == nil:
av_frame_free(addr output)
error "Could not allocate scaled frame"
view.format = AV_PIX_FMT_YUV420P.cint
view.colorspace = tag.space
view.color_range = tag.range
view.width = scaledW
view.height = scaledH
# Propagate interlaced flags so sws_frame_setup doesn't reject mismatched frames.
# AV_FRAME_FLAG_INTERLACED = 1<<3, AV_FRAME_FLAG_TOP_FIELD_FIRST = 1<<4
view.flags = src.flags and (8 or 16).cint
for p in 0 .. 2:
let (dx, dy) = (if p == 0: (ox.int, oy.int) else: (ox.int div 2, oy.int div 2))
view.linesize[p] = output.linesize[p]
view.data[p] = cast[ptr uint8](cast[int](output.data[p]) +
dy * output.linesize[p].int + dx)
# One context for the render: it keeps its setup until the sizes or
# formats it's given change, which building one per frame repeated.
if swsCtx == nil:
swsCtx = sws_alloc_context()
if swsCtx == nil:
av_frame_free(addr view)
av_frame_free(addr output)
error "Could not allocate sws context in scaleWithPad"
swsCtx.setOpt("threads", 0)
let scaleRet = sws_scale_frame(swsCtx, view, src)
av_frame_free(addr view)
if scaleRet < 0:
av_frame_free(addr output)
error &"Could not scale frame in scaleWithPad: {scaleRet}"
return output
func scaledVideoResolution*(resolution: (int32, int32),
scale: float64): (int32, int32) =
if scale == 1.0:
return resolution
(
max(int32(round(resolution[0].float64 * scale)) and not 1'i32, 2),
max(int32(round(resolution[1].float64 * scale)) and not 1'i32, 2),
)
proc makeNewVideoFrames*(output: var OutputContainer, timeline: ptr v3,
args: mainArgs,
video: VideoSettings, myCache: MediaCache, startIndex = 0'i64,
stop: ptr Atomic[bool] = nil, keep: VideoSources = nil):
(ptr AVCodecContext, ptr AVStream, iterator(): (ptr AVFrame, int64)) =
## Frames from `startIndex` on. A set `stop` ends the iterator at its next
## call, freeing what it holds (a preview abandons a render this way).
## With `keep`, sources' decoders come from it and stay in it at the end,
## for the next render to pick up where this one left off.
# 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[]
# One state object per source (decoders, seek bookkeeping, still/held frame
# caches, loop accounting). Still-image sources (overlay logos/watermarks)
# decode a single frame that is held for the clip's whole duration in `still`.
let sources = (if keep != nil: keep else: newVideoSources())
template srcs: untyped = sources.srcs
# Within a single timeline frame, two layers can reference the same source at
# the same source-frame index (e.g. a clip composited over itself). The shared
# per-source decoder can only be at one position, so memoize the raw decoded
# frame per (src, index) for the duration of one timeline frame; cleared at the
# top of each iteration.
var decodedCache = initTable[(ptr string, int), ptr AVFrame]()
var pix_fmt = AV_PIX_FMT_YUV420P
let targetFps = tl.tb
for layer in tl.v:
for clip in layer:
if clip.src != nil and myCache.getContainer(clip.src).video.len == 0:
error &"{clip.src[]} has no video stream"
for src in tl.uniqueSources:
# getContainer turns a missing/unreadable source (e.g. `add:gone.mp4`)
# into a clean error instead of an unhandled IOError.
discard myCache.getContainer(src)
if src in srcs:
# Kept from an earlier render, whose frame numbers usedAt counts in.
for d in srcs[src].decoders: d.usedAt = -1
continue
# Per-source state with mutable-decode defaults. Decoding always begins on a
# keyframe, so frame 0 is always a valid seek point (observedKeyframes starts
# at @[0]); decoder/isStill below fill in for sources that have a video stream.
srcs[src] = SrcState(observedKeyframes: @[0])
# Audio-only sources (e.g. the .mp3 behind a synthesized video canvas) have
# no video stream to decode.
if myCache.cns[src].video.len > 0:
let decoderCtx = initDecoder(myCache.cns[src].video[0].codecpar)
decoderCtx.thread_type = FF_THREAD_FRAME or FF_THREAD_SLICE
srcs[src].decoders.add newDecState(myCache.cns[src], decoderCtx, false)
# An image source is a single still: an image codec read by an image
# demuxer, or a stream that reports exactly one frame. The demuxer check
# matters because these codecs also carry real video (MJPEG in avi/mov).
let vstream = myCache.cns[src].video[0]
let imageCodecs = [ID_PNG, ID_JPEG, ID_WEBP, ID_BMP, ID_TIFF]
let demuxer = $myCache.cns[src].formatContext.iformat.name
srcs[src].isStill = vstream.nb_frames == 1 or
(vstream.codecpar.codec_id in imageCodecs and
(demuxer == "image2" or demuxer.endsWith("_pipe")))
let (targetWidth, targetHeight) = scaledVideoResolution(tl.res, video.scale)
# Configured effect graphs, static source rotations included, one per key.
# A frame can run several (a chain like `blur,brightness`, or an effect on
# each layer), and a single slot would have them rebuild each other every
# frame. A graph is freed once a whole frame passes without it, so an
# animated effect, whose key changes every frame, holds at most two.
var fxGraphs: seq[tuple[key: GraphKey, graph: Graph, usedAt: int64]] = @[]
var fxGraph: Graph = nil # the one `withFxGraph` last selected
# A filter that syncs its inputs (overlay, alphamerge, maskedmerge) emits
# once each holds a frame of one timestamp, so a kept graph of them is
# given every set of frames at the next one.
var syncPts = 0'i64
# Mask/confine mattes (gray8), one per shape and size so the per-pixel shape
# math runs once, not every frame, however many layers are masked. Freed
# like the graphs, once a whole frame passes without it.
var mattes: seq[tuple[key: MatteKey, matte: ptr AVFrame, usedAt: int64]] = @[]
let needsScaling = video.scale != 1.0
debug &"Creating video stream with codec: {video.codec}"
let wanted = initCodec(video.codec)
if wanted != nil and wanted.`type` != AVMEDIA_TYPE_VIDEO:
error &"{video.codec} isn't a video encoder"
var (outputStream, encoderCtx) = output.addStream(video.codec, targetFps,
lang = tl.langs[0], width = targetWidth, height = targetHeight)
var codec = encoderCtx.codec
if codec.id == ID_HEVC:
const codecTag = fourccToInt("hvc1") # for QuickTime
outputStream.codecpar.codec_tag = codecTag
encoderCtx.codec_tag = codecTag
encoderCtx.framerate = targetFps
encoderCtx.thread_type = FF_THREAD_FRAME or FF_THREAD_SLICE
# FFmpeg's default is one thread, which only encoders with their own
# default (libx264) override. The web build's workers come from a fixed
# pool, so it keeps the default.
when not defined(emscripten):
encoderCtx.thread_count = 0
# Reference source for encoder config (color/pix_fmt/SAR): the first real,
# non-still video in layer and clip order, so the base layer wins. Not from
# uniqueSources, whose order follows the `ptr string` keys' addresses and so
# changes from run to run. An audio-only `add` timeline may have only still
# images over a synthesized background, in which case yuv420p defaults are
# used.
var firstSrc: ptr string = nil
block pick:
for layer in tl.v:
for clip in layer:
let s = clip.src
if s != nil and myCache.cns[s].video.len > 0 and not srcs[s].isStill:
firstSrc = s
break pick
# Don't inherit color tags / SAR from a still image. PNGs are tagged full-range
# (which makes the H.264 encoder emit deprecated yuvj420p), so when the only
# reference is a still (e.g. an audio-only `add` over a synthesized canvas),
# keep the encoder's limited-range yuv420p defaults instead. firstSrc is nil
# when nothing in the timeline carries video at all, e.g. audio plus a lone
# `add:confetti` generator; the same defaults cover that.
if firstSrc != nil and not srcs[firstSrc].isStill:
let src = myCache.cns[firstSrc]
let color_range = src.video[0].codecpar.color_range
let colorspace = src.video[0].codecpar.color_space
let color_prim = src.video[0].codecpar.color_primaries
let color_trc = src.video[0].codecpar.color_trc
if color_range in [1, 2]:
encoderCtx.color_range = color_range
if colorspace in [0, 1] or (colorspace >= 3 and colorspace < 16):
encoderCtx.colorspace = colorspace
if color_prim == 1 or (color_prim >= 4 and color_prim < 17):
encoderCtx.color_primaries = color_prim
if color_trc == 1 or (color_trc >= 4 and color_trc < 22):
encoderCtx.color_trc = color_trc
let sar = av_guess_sample_aspect_ratio(src.formatContext, src.video[0], nil)
if sar.isValid:
encoderCtx.sample_aspect_ratio = sar
if video.bitrate >= 0:
encoderCtx.bit_rate = video.bitrate
debug(&"video bitrate: {encoderCtx.bit_rate}")
else:
debug(&"[auto] video bitrate: {encoderCtx.bit_rate}")
for src, cn in myCache.cns:
if len(cn.video) > 0 and src in srcs:
let st = srcs[src]
let stream = cn.video[0]
let defaultInterval = toInt(targetFps * AVRational(num: 5, den: 1))
# avg_frame_rate can be 0/0 for streams with no declared frame rate; use
# the timeline rate for both frame indexing and seek timestamp conversion.
st.frameRate =
if stream.avg_frame_rate.isValid: stream.avg_frame_rate else: targetFps
let fps = st.frameRate.float
if args.noSeek:
st.kfFrames = @[]
st.hasKfIndex = false
st.kfInterval = high(int)
else:
let kf = buildKeyframeIndex(stream, fps, defaultInterval)
st.kfFrames = kf.frames
st.kfInterval = kf.avgInterval
st.hasKfIndex = kf.hasIndex
if kf.hasIndex:
debug &"Source {src[]}: {kf.frames.len} keyframes indexed, " &
&"avg interval: {kf.avgInterval} frames"
else:
debug &"Source {src[]}: no index entries, using estimated " &
&"interval: {kf.avgInterval} frames"
if src == firstSrc and not st.isStill and
encoderCtx.pix_fmt != AV_PIX_FMT_NONE:
pix_fmt = AVPixelFormat(cn.video[0].codecpar.format)
let userFmt = video.pixFmt != ""
if userFmt:
pix_fmt = av_get_pix_fmt(cstring(video.pixFmt))
if pix_fmt == AV_PIX_FMT_NONE:
error &"Unknown pixel format: {video.pixFmt}"
let pixFmts = codec.supportedPixFmts
var needValidFmt = true
if pixFmts != nil:
var i = 0
while pixFmts[i].cint != -1:
if pix_fmt == pixFmts[i]:
needValidFmt = false
break
i += 1
if needValidFmt:
# A format the user asked for by name must not be silently swapped.
if userFmt and pixFmts != nil:
error &"Encoder {codec.name} does not support pixel format: {video.pixFmt}"
if pixFmts != nil:
let best = avcodec_find_best_pix_fmt_of_list(pixFmts, pix_fmt, 0, nil)
pix_fmt = if best != AV_PIX_FMT_NONE: best else: AV_PIX_FMT_YUV420P
else:
pix_fmt = AV_PIX_FMT_YUV420P
if video.profile != "":
encoderCtx.setProfileOrErr(video.profile)
encoderCtx.pix_fmt = pix_fmt
resolveEncoderContext(encoderCtx)
codec = encoderCtx.codec
if codec.id == ID_HEVC:
encoderCtx.priv_data.setOpt("x265-params", "log-level=error")
if codec.id == ID_VP9:
# libvpx splits a frame among its threads by tile columns alone, a few
# at most at HD sizes; row-mt lets them share the rows as well.
encoderCtx.priv_data.setOpt("row-mt", 1)
if video.crf >= 0:
encoderCtx.priv_data.setOpt("crf", video.crf)
if video.preset != "":
encoderCtx.priv_data.setOpt("preset", video.preset)
if video.gop >= 1:
encoderCtx.gop_size = video.gop.cint
elif args.fragmented and not args.noFragmented:
# frag_keyframe only cuts a fragment at a keyframe, so the default keyint
# would hold back the first fragment for seconds of media.
encoderCtx.gop_size = max(1, int(round(tl.tb.float))).cint
# Tags inherited from an RGB source (matrix RGB, full range) describe the
# source, not a YUV encode of it; frames are converted with swscale's
# defaults, so leave the output's tags to match those (#1289).
if not pix_fmt.isRgb and encoderCtx.colorspace.int == 0: # AVCOL_SPC_RGB
encoderCtx.colorspace = 2 # AVCOL_SPC_UNSPECIFIED
encoderCtx.color_range = 0 # AVCOL_RANGE_UNSPECIFIED
encoderCtx.open()
pix_fmt = encoderCtx.pix_fmt
if avcodec_parameters_from_context(outputStream.codecpar, encoderCtx) < 0:
error "Could not copy encoder parameters to stream"
let templateVid =
if tl.templateFile != nil: myCache.getContainer(tl.templateFile).video
else: @[]
if templateVid.len > 0:
let srcPar = templateVid[0].codecpar
let sd = av_packet_side_data_get(srcPar.coded_side_data,
srcPar.nb_coded_side_data, AV_PKT_DATA_DISPLAYMATRIX)
if sd != nil and sd.size > 0:
let dstPar = outputStream.codecpar
let dst = av_packet_side_data_new(addr dstPar.coded_side_data,
addr dstPar.nb_coded_side_data, AV_PKT_DATA_DISPLAYMATRIX, sd.size, 0)
if dst != nil:
copyMem(dst.data, sd.data, sd.size)
let graphTb = av_inv_q(targetFps)
let solidTag: YuvTag = (
(if encoderCtx.colorspace.int == 0: 2.cint else: encoderCtx.colorspace),
encoderCtx.color_range)
let bgRgb = tl.bg.toRgb(solidTag.space.int, solidTag.range.int == 2)
let bg = bgRgb.toString
func keyColor(effect: Action, frame: ptr AVFrame): string =
effect.color.toRgb(frame.colorspace.int, frame.color_range.int == 2).toString
proc bufArgsOf(frame: ptr AVFrame): string =
## Buffer-source args for feeding `frame` into a graph; only built when a
## graph is actually (re)configured, never on the per-frame reuse path.
&"video_size={frame.width}x{frame.height}:" &
&"pix_fmt={$AVPixelFormat(frame.format)}:time_base={graphTb}:pixel_aspect=1/1"
# Scaling has stable input/output geometry, so keep one libswscale
# context instead of sending every frame through a filter graph.
var scaleCtx: ptr SwsContext = nil
var padCtx: ptr SwsContext = nil # scaleWithPad's
if needsScaling:
scaleCtx = sws_alloc_context()
if scaleCtx == nil:
error "Failed to allocate proxy scale sws context"
scaleCtx.setOpt("threads", 0)
# One sws context for the per-frame pixel format conversion. It is kept
# even when the stream's format matches the output: a decoder may still
# hand back another layout (a browser's NV12 for a yuv420p stream), and
# swscale only initializes the context on the first frame that needs it.
var reformatCtx = sws_alloc_context()
if reformatCtx == nil:
error "Failed to allocate reformat sws context"
reformatCtx.setOpt("threads", 0)
# Allocated on the first zoom; swscale rebuilds it itself when the geometry
# changes, so a constant zoom pays the init cost once.
var zoomCtx: ptr SwsContext = nil
# Likewise for per-frame conversions elsewhere, each kept to one direction
# so its geometry and formats stay put from frame to frame.
var fxConvCtx: ptr SwsContext = nil # an effect's format
var overlayCtx: ptr SwsContext = nil # a sub-pixel overlay's scale
var toRgbCtx: ptr SwsContext = nil # into a transition
var fromRgbCtx: ptr SwsContext = nil # out of a transition
template lazyCtx(c: var ptr SwsContext): ptr SwsContext =
(if c == nil: c = newSwsCtx(); c)
var framesSaved = 0
var frameNo = -1'i64 # the timeline frame being built
var nullFrame = makeSolid(targetWidth, targetHeight, tl.bg, solidTag)
if nullFrame == nil:
error "Could not allocate fallback video frame"
var frame: ptr AVFrame = av_frame_clone(nullFrame)
var objList: seq[VideoFrame] = @[]
var lastProcessedFrame: ptr AVFrame = nil
var burner = SubBurner()
# What the cached single-layer frame was decoded from: (src, index, rotate).
var lastDecoded: (ptr string, int, float32) = (nil, -1, 0.0'f32)
let isLinear = tl.isLinear
debug &"isLinear: {isLinear}"
proc cachedFxGraph(key: GraphKey): Graph =
## The configured graph for `key`, marked as used by this frame, or nil.
for e in fxGraphs.mitems:
if e.key == key:
e.usedAt = frameNo
return e.graph
nil
# Point `fxGraph` at the graph for `key`. When there is none yet, `build`
# must add nodes to the new, empty `fxGraph` and configure it.
template withFxGraph(key: GraphKey, build: untyped) =
let k = key
fxGraph = cachedFxGraph(k)
if fxGraph == nil:
fxGraph = newGraph()
build
fxGraphs.add (k, fxGraph, frameNo)
proc dropIdleFxGraphs() =
## Free the graphs the previous frame didn't use.
var kept = 0
for i in 0 ..< fxGraphs.len:
if fxGraphs[i].usedAt >= frameNo - 1:
fxGraphs[kept] = fxGraphs[i]
inc kept
else:
fxGraphs[i].graph.cleanup()
fxGraphs.setLen(kept)
proc dropIdleMattes() =
## Free the mattes the previous frame didn't use.
var kept = 0
for i in 0 ..< mattes.len:
if mattes[i].usedAt >= frameNo - 1:
mattes[kept] = mattes[i]
inc kept
else:
av_frame_free(addr mattes[i].matte)
mattes.setLen(kept)
proc keyOverBg(frame0: ptr AVFrame, effect: Action): ptr AVFrame =
var frame = frame0
let w = frame.width
let h = frame.height
let col = keyColor(effect, frame)
let isChroma = effect.kind == actChromaKey
var bgFrame = makeSolid(w, h, tl.bg, solidTag)
withFxGraph(fxId(effect.kind, frame, f0 = effect.similar, f1 = effect.blend,
i0 = 1, col = packRGB(effect.color))):
let bgSrc = fxGraph.add("buffer", bufArgsOf(bgFrame))
let fgSrc = fxGraph.add("buffer", bufArgsOf(frame))
let toAlpha = fxGraph.add("format",
"pix_fmts=" & (if isChroma: "yuva420p" else: "rgba"))
let keyer = fxGraph.add((if isChroma: "chromakey" else: "colorkey"),
&"{col}:{effect.similar}:{effect.blend}")
let ov = fxGraph.add("overlay", "format=yuv420")
discard fxGraph.linkNodes(fgSrc, toAlpha, keyer)
fxGraph.link(bgSrc, ov, 0, 0) # background on the bottom pad
fxGraph.link(keyer, ov, 0, 1) # keyed frame on top
fxGraph.link(ov, fxGraph.add("buffersink"))
fxGraph.configure()
inc syncPts
bgFrame.pts = syncPts
frame.pts = syncPts
fxGraph.move(bgFrame, 0)
fxGraph.move(frame, 1)
result = fxGraph.pull()
result.pts = 0
av_frame_free(addr bgFrame)
av_frame_free(addr frame)
proc cachedMatte(frame: ptr AVFrame, effect: Action): ptr AVFrame =
## The matte for `effect` at `frame`'s size, built when there is none yet.
## Caller must NOT free the result.
let k: MatteKey = (w: frame.width, h: frame.height,
kind: effect.kind, x: effect.mX, y: effect.mY, wd: effect.mW, ht: effect.mH,
radius: effect.mRadius, feather: effect.mFeather, invert: effect.mInvert,
polyXs: effect.mPolyXs, polyYs: effect.mPolyYs)
for e in mattes.mitems:
if e.key == k:
e.usedAt = frameNo
return e.matte
let matte =
if effect.kind in {actMaskPoly, actConfinePoly}:
buildPolyMaskMatte(frame.width, frame.height, effect)
else: buildMaskMatte(frame.width, frame.height, effect)
mattes.add (k, matte, frameNo)
matte
proc alphamergeOnto(frame0, matte: ptr AVFrame): ptr AVFrame =
## Set `frame`'s alpha from the gray matte (cheap; no per-pixel geq).
var frame = frame0
var m = av_frame_clone(matte) # cached matte; push a fresh ref
withFxGraph(fxId(actMask, frame, i0 = 1)):
let fSrc = fxGraph.add("buffer", bufArgsOf(frame))
let mSrc = fxGraph.add("buffer", bufArgsOf(m))
let toGbrp = fxGraph.add("format", "pix_fmts=gbrp")
let am = fxGraph.add("alphamerge")
let toRgba = fxGraph.add("format", "pix_fmts=rgba")
let sink = fxGraph.add("buffersink")
discard fxGraph.linkNodes(fSrc, toGbrp)
fxGraph.link(toGbrp, am, 0, 0)
fxGraph.link(mSrc, am, 0, 1)
fxGraph.link(am, toRgba)
fxGraph.link(toRgba, sink)
fxGraph.configure()
inc syncPts
frame.pts = syncPts
m.pts = syncPts
fxGraph.move(frame, 0)
fxGraph.move(m, 1)
result = fxGraph.pull()
result.pts = 0
av_frame_free(addr m)
av_frame_free(addr frame)
proc overBg(frame0: ptr AVFrame): ptr AVFrame =
## Flatten an alpha-shaped rgba frame over a solid `-bg` (base-track mask).
var top = frame0
var bgFrame = makeSolid(top.width, top.height, tl.bg, solidTag)
withFxGraph(fxId(actMask, top, i0 = 2)):
let bgSrc = fxGraph.add("buffer", bufArgsOf(bgFrame))
let fgSrc = fxGraph.add("buffer", bufArgsOf(top))
let ov = fxGraph.add("overlay", "format=yuv420")
fxGraph.link(bgSrc, ov, 0, 0)
fxGraph.link(fgSrc, ov, 0, 1)
fxGraph.link(ov, fxGraph.add("buffersink"))
fxGraph.configure()
inc syncPts
bgFrame.pts = syncPts
top.pts = syncPts
fxGraph.move(bgFrame, 0)
fxGraph.move(top, 1)
result = fxGraph.pull()
result.pts = 0
av_frame_free(addr bgFrame)
av_frame_free(addr top)
proc maskedMergeRegion(saved, effected, matte: ptr AVFrame): ptr AVFrame =
## Merge `effected` over `saved` weighted by the gray `matte` (in gbrp, so
## the per-plane merge is clean), then back to the original format.
let origFmt = AVPixelFormat(saved.format)
var m = av_frame_clone(matte) # cached matte; push a fresh ref
withFxGraph(fxId(actConfine, saved, i0 = effected.width, i1 = effected.height,
i2 = effected.format)):
let bSrc = fxGraph.add("buffer", bufArgsOf(saved))
let oSrc = fxGraph.add("buffer", bufArgsOf(effected))
let mSrc = fxGraph.add("buffer", bufArgsOf(m))
let bFmt = fxGraph.add("format", "pix_fmts=gbrp")
let oFmt = fxGraph.add("format", "pix_fmts=gbrp")
let mFmt = fxGraph.add("format", "pix_fmts=gbrp")
let mm = fxGraph.add("maskedmerge")
let toOrig = fxGraph.add("format", &"pix_fmts={$origFmt}")
let sink = fxGraph.add("buffersink")
discard fxGraph.linkNodes(bSrc, bFmt)
discard fxGraph.linkNodes(oSrc, oFmt)
discard fxGraph.linkNodes(mSrc, mFmt)
fxGraph.link(bFmt, mm, 0, 0)
fxGraph.link(oFmt, mm, 0, 1)
fxGraph.link(mFmt, mm, 0, 2)
fxGraph.link(mm, toOrig)
fxGraph.link(toOrig, sink)
fxGraph.configure()
inc syncPts
saved.pts = syncPts
effected.pts = syncPts
m.pts = syncPts
fxGraph.pushIdx(0, saved)
fxGraph.pushIdx(1, effected)
fxGraph.pushIdx(2, m)
result = fxGraph.pull()
result.pts = 0
av_frame_free(addr m)
proc applyEffects(frame0: ptr AVFrame, effects: Actions, local, clipDur: int,
isOverlay = false, src: ptr string = nil, srcSecs = 0.0): ptr AVFrame =
## Apply one clip's effect chain to a frame, returning the (possibly new)
## frame. Shared by the single-layer path and per-clip compositing. `isOverlay`
## is true for higher composited layers, which want transparent (not bg) fill
## from `spin`.
var frame = frame0
let fps = tl.tb.float
# `confine` state: the active region's matte (lazily (re)built at the frame
# size of the next confined effect) and whether this iteration's effect is
# restricted to it.
var confineActive = false
var confineThis = false
# The chain's scale and turn act as one, where the first of them is: one
# pass, so nothing is cut off at the edge between them.
var placeDone = false
var confineEffect: Action
# An animated action's ramp at this frame, eased and timed as it says
# (by default linear over the whole clip).
template sample(e: Action, kf: seq[float32], kt: seq[KfTime]): float32 =
e.ramp(kf, kt, frameSpan(clipDur, fps)).at(local)
# Run `body`, which replaces `frame` with its effected self. When the
# active `confine` covers this effect, merge only the masked region back
# over the untouched frame.
template confined(body: untyped) =
if confineThis:
let matte = cachedMatte(frame, confineEffect)
let saved = av_frame_clone(frame)
body
let effected = frame
frame = maskedMergeRegion(saved, effected, matte)
av_frame_free(addr saved)
av_frame_free(addr effected)
else:
body
template throughFxGraph() =
fxGraph.move(frame)
av_frame_free(addr frame)
frame = fxGraph.pull()
# Run `frame` through the effect graph identified by `key`, which `build`
# makes as `withFxGraph` says.
template runFx(key: GraphKey, build: untyped) =
withFxGraph(key, build)
confined:
throughFxGraph()
# Convert `frame` to pixel format `to`. The key leaves out what the effect
# is set to, so an animated one keeps its graphs from frame to frame
# instead of building one per value.
template convertTo(kind: ActionKind, to: AVPixelFormat) =
withFxGraph(fxId(kind, frame, i0 = 1, i1 = int32(to))):
let bufferSrc = fxGraph.add("buffer", bufArgsOf(frame))
let conv = fxGraph.add("format", "pix_fmts=" & $to)
let bufferSink = fxGraph.add("buffersink")
fxGraph.linkNodes(bufferSrc, conv, bufferSink).configure()
throughFxGraph()
for effect in effects:
confineThis = confineActive and effect.kind in confinable
case effect.kind:
of actSpeed, actVolume, actDeesser, actDuck, actPitch, actTone, actConvolve,
actHighpass, actLowpass, actDehum, actPos, actRotate, actLoop: discard
of actScale, actTurn:
# An overlay is scaled and turned where it's placed, about its center.
if not (isOverlay or placeDone):
placeDone = true
let (sx, sy, deg) = scaleTurnOf(effects)
if not (sx == 1.0'f32 and sy == 1.0'f32 and mod360(deg) == 0):
let w = frame.width
let h = frame.height
let sw = max(2.cint, cint(round(w.float32 * sx))) and not 1.cint
let sh = max(2.cint, cint(round(h.float32 * sy))) and not 1.cint
runFx(fxId(actScale, frame, f0 = sx, f1 = deg, f2 = sy)):
# rotate turns about the center of a frame of the canvas's size,
# cropping what's past it and filling what's uncovered with bg.
let nodes = @[fxGraph.add("buffer", bufArgsOf(frame)),
fxGraph.add("scale", &"{sw}:{sh}"),
fxGraph.add("rotate", &"a={deg}*PI/180:ow={w}:oh={h}:c={bg}"),
fxGraph.add("buffersink")]
fxGraph.linkNodes(nodes).configure()
of actSpin:
let rate = effect.sRate
let startDeg = rotDeg(effect.sStart)
let w = frame.width
let h = frame.height
frame.pts = local.int64
runFx(fxId(actSpin, frame, overlay = isOverlay, f0 = startDeg, f1 = rate)):
# Spin within a constant square sized to the diagonal, so no angle clips
# the picture. Overlays fill the exposed corners transparently (only the
# picture shows over the base); the base layer fills them with bg.
let side = cint(int(ceil(hypot(w.float, h.float))) + 1) and not 1.cint
let aExpr = &"a=({startDeg}+({rate})*t)*PI/180:ow={side}:oh={side}"
var nodes: seq[ptr AVFilterContext] =
@[fxGraph.add("buffer", bufArgsOf(frame))]
if isOverlay:
# Convert to rgba first so the rotate fill (and exposed corners) can
# be transparent.
nodes.add fxGraph.add("format", "pix_fmts=rgba")
nodes.add fxGraph.add("rotate", aExpr & ":c=black@0")
else:
nodes.add fxGraph.add("rotate", aExpr & &":c={bg}")
nodes.add fxGraph.add("buffersink")
fxGraph.linkNodes(nodes).configure()
if not isOverlay:
# Base layer must stay canvas-sized: shrink the contained square back
# to the original frame size, centered with bg padding.
let fitted = scaleWithPad(frame, w, h, tl.bg, solidTag, padCtx)
if fitted != frame:
av_frame_free(addr frame)
frame = fitted
of actZoom:
let z = sample(effect, effect.kf, effect.kt)
if z != 1.0'f32:
let origW = frame.width
let origH = frame.height
if zoomCtx == nil:
zoomCtx = sws_alloc_context()
if zoomCtx == nil:
error "Failed to allocate zoom sws context"
zoomCtx.setOpt("threads", 0)
let scaledW = max(cint(float(origW) * z), 2)
let scaledH = max(cint(float(origH) * z), 2)
if z > 1.0:
# Scale only the source region that stays visible instead of the whole
# frame, which at z=3 is 9x the pixels. The window is then placed
# where the full-frame scale would have put it, in output pixels, so
# an animated zoom doesn't step by whole source pixels.
if AVPixelFormat(frame.format).isBitstream:
# Cropping moves data pointers, which can't land mid-byte, so
# FFmpeg skips the left and top crop for 1-bit formats.
let gray = frame.reformat(AV_PIX_FMT_GRAY8)
av_frame_free(addr frame)
frame = gray
let d = av_pix_fmt_desc_get(AVPixelFormat(frame.format))
let hstep = 1.cint shl d.log2_chroma_w
let vstep = 1.cint shl d.log2_chroma_h
let x = zoomSpan(origW, scaledW, hstep)
let y = zoomSpan(origH, scaledH, vstep)
cropView(frame, x.start, y.start, origW - x.start - x.len,
origH - y.start - y.len)
let scaledFrame = frame.reformat(AVPixelFormat(frame.format),
x.scaledLen, y.scaledLen, zoomCtx)
if scaledFrame != frame:
av_frame_free(addr frame)
frame = scaledFrame
let cx = clamp(cint(round(x.offset / float(hstep))) * hstep, 0,
(x.scaledLen - origW) div hstep * hstep)
let cy = clamp(cint(round(y.offset / float(vstep))) * vstep, 0,
(y.scaledLen - origH) div vstep * vstep)
cropView(frame, cx, cy, x.scaledLen - origW - cx, y.scaledLen - origH - cy)
else:
let scaledFrame = frame.reformat(AVPixelFormat(frame.format), scaledW,
scaledH, zoomCtx)
if scaledFrame != frame:
av_frame_free(addr frame)
frame = scaledFrame
runFx(fxId(actZoom, frame, i0 = origW.int32, i1 = origH.int32)):
let bufferSrc = fxGraph.add("buffer", bufArgsOf(frame))
let pad = fxGraph.add("pad", &"{origW}:{origH}:-1:-1:color={bg}")
let bufferSink = fxGraph.add("buffersink")
fxGraph.linkNodes(bufferSrc, pad, bufferSink).configure()
of actHflip, actVflip, actInvert, actErosion:
runFx(fxId(effect.kind, frame)):
let filterName = case effect.kind
of actHflip: "hflip"
of actVflip: "vflip"
of actErosion: "erosion"
else: "negate"
let bufferSrc = fxGraph.add("buffer", bufArgsOf(frame))
let filt = fxGraph.add(filterName)
let bufferSink = fxGraph.add("buffersink")
fxGraph.linkNodes(bufferSrc, filt, bufferSink).configure()
of actBlur:
let sigma = sample(effect, effect.kf, effect.kt)
if sigma > 0.0'f32:
runFx(fxId(actBlur, frame, f0 = sigma)):
let bufferSrc = fxGraph.add("buffer", bufArgsOf(frame))
let filt = fxGraph.add("gblur", &"sigma={sigma}")
let bufferSink = fxGraph.add("buffersink")
fxGraph.linkNodes(bufferSrc, filt, bufferSink).configure()
of actBrightness:
let b = sample(effect, effect.kf, effect.kt)
if b != 0.0'f32:
let orig = AVPixelFormat(frame.format)
if effect.kf.len > 1:
# A ramp has another value each frame, and lutrgb takes a new one
# only by being rebuilt. So only the conversions are graphs, and
# the table is applied here.
confined:
convertTo(actBrightness, AV_PIX_FMT_RGB24)
applyLut(frame, lutOf(1, b * 255.0'f32), 0, 1, 3)
convertTo(actBrightness, orig)
else:
# A fixed value keeps its graph, and lutrgb's lookup is threaded.
runFx(fxId(actBrightness, frame, f0 = b)):
let bufferSrc = fxGraph.add("buffer", bufArgsOf(frame))
let toRgb = fxGraph.add("format", "pix_fmts=rgb24")
let expr = brightnessLutExpr(b)
let lut = fxGraph.add("lutrgb", &"r={expr}:g={expr}:b={expr}")
let toOrig = fxGraph.add("format", "pix_fmts=" & $orig)
let bufferSink = fxGraph.add("buffersink")
fxGraph.linkNodes(bufferSrc, toRgb, lut, toOrig, bufferSink).configure()
of actLuv:
if not (effect.brighthue == luvBrighthueId and
effect.contrast == luvContrastId and
effect.saturation == luvSaturationId):
let b = effect.brighthue
let c = effect.contrast
let s = effect.saturation
runFx(fxId(actLuv, frame, f0 = b, f1 = c, f2 = s)):
let expr = luvLutExprs(b, c, s)
let bufferSrc = fxGraph.add("buffer", bufArgsOf(frame))
let toYuv = fxGraph.add("format", "pix_fmts=yuv444p")
let lut = fxGraph.add("lutyuv", &"y={expr.y}:u={expr.u}:v={expr.v}")
let toOrig = fxGraph.add("format", &"pix_fmts={$AVPixelFormat(frame.format)}")
let bufferSink = fxGraph.add("buffersink")
fxGraph.linkNodes(bufferSrc, toYuv, lut, toOrig, bufferSink).configure()
of actOpacity:
let o = sample(effect, effect.kf, effect.kt)
if o < 1.0'f32:
# As for brightness: a ramp's table is applied here.
let animated = effect.kf.len > 1
if isOverlay:
if animated:
confined:
convertTo(actOpacity, AV_PIX_FMT_RGBA)
applyLut(frame, lutOf(o, 0), 3, 4, 4)
else:
runFx(fxId(actOpacity, frame, overlay = true, f0 = o)):
let bufferSrc = fxGraph.add("buffer", bufArgsOf(frame))
let toRgba = fxGraph.add("format", "pix_fmts=rgba")
let lut = fxGraph.add("lutrgb", &"a=val*{o}")
let bufferSink = fxGraph.add("buffersink")
fxGraph.linkNodes(bufferSrc, toRgba, lut, bufferSink).configure()
else:
let orig = AVPixelFormat(frame.format)
let bgPart = [(1.0'f32 - o) * float32(bgRgb.red),
(1.0'f32 - o) * float32(bgRgb.green), (1.0'f32 - o) * float32(bgRgb.blue)]
if animated:
confined:
convertTo(actOpacity, AV_PIX_FMT_RGB24)
for c in 0 ..< 3:
applyLut(frame, lutOf(o, bgPart[c]), c, 3, 3)
convertTo(actOpacity, orig)
else:
runFx(fxId(actOpacity, frame, f0 = o)):
let bufferSrc = fxGraph.add("buffer", bufArgsOf(frame))
let toRgb = fxGraph.add("format", "pix_fmts=rgb24")
let lut = fxGraph.add("lutrgb", &"r=val*{o}+{bgPart[0]}:" &
&"g=val*{o}+{bgPart[1]}:b=val*{o}+{bgPart[2]}")
let toOrig = fxGraph.add("format", "pix_fmts=" & $orig)
let bufferSink = fxGraph.add("buffersink")
fxGraph.linkNodes(bufferSrc, toRgb, lut, toOrig, bufferSink).configure()
of actLens:
let k1 = effect.k1
let k2 = effect.k2
if not (k1 == 0.0'f32 and k2 == 0.0'f32):
runFx(fxId(actLens, frame, f0 = k1, f1 = k2)):
let bufferSrc = fxGraph.add("buffer", bufArgsOf(frame))
let filt = fxGraph.add("lenscorrection", &"k1={k1}:k2={k2}:fc={bg}")
let bufferSink = fxGraph.add("buffersink")
fxGraph.linkNodes(bufferSrc, filt, bufferSink).configure()
of actDrawbox:
if effect.dbColor.yuv and AVPixelFormat(frame.format) in
[AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUVJ420P]:
if av_frame_make_writable(frame) < 0:
error "Can't make frame writable"
fillBox(frame, effect.dbX, effect.dbY, effect.dbW, effect.dbH, effect.dbColor)
else:
runFx(fxId(actDrawbox, frame, i0 = effect.dbX, i1 = effect.dbY,
i2 = effect.dbW, i3 = effect.dbH, col = packRGB(effect.dbColor))):
let col = effect.dbColor.toRgb(frame.colorspace.int,
frame.color_range.int == 2).toString
let bufferSrc = fxGraph.add("buffer", bufArgsOf(frame))
let filt = fxGraph.add("drawbox",
# replace=1: on a generator/keyed layer the canvas alpha is 0, and
# compositing an opaque box over it would leave it invisible.
&"x={effect.dbX}:y={effect.dbY}:w={effect.dbW}:h={effect.dbH}" &
&":color={col}:t=fill:replace=1")
let bufferSink = fxGraph.add("buffersink")
fxGraph.linkNodes(bufferSrc, filt, bufferSink).configure()
of actColorKey, actChromaKey:
if not isOverlay:
# Base layer: no lower track to reveal, so replace the keyed color with
# the timeline background instead of making it transparent.
frame = keyOverBg(frame, effect)
else:
runFx(fxId(effect.kind, frame, f0 = effect.similar, f1 = effect.blend,
col = packRGB(effect.color))):
let col = keyColor(effect, frame)
var nodes = @[fxGraph.add("buffer", bufArgsOf(frame))]
if effect.kind == actChromaKey:
# chromakey keys in YUV-with-alpha; convert in, then back to rgba so
# the composited overlay keeps its alpha channel.
nodes.add fxGraph.add("format", "pix_fmts=yuva420p")
nodes.add fxGraph.add("chromakey", &"{col}:{effect.similar}:{effect.blend}")
nodes.add fxGraph.add("format", "pix_fmts=rgba")
else:
nodes.add fxGraph.add("colorkey", &"{col}:{effect.similar}:{effect.blend}")
nodes.add fxGraph.add("buffersink")
fxGraph.linkNodes(nodes).configure()
of actChoke:
# Choke (shrink) the alpha matte a key produced, to cut off the spill
# fringe. Only overlay layers carry alpha; the base track keys over bg
# (no matte), so there is nothing to choke there.
if isOverlay and hasAlpha(AVPixelFormat(frame.format)):
let n = max(1, int(effect.chokeN))
runFx(fxId(actChoke, frame, i0 = n.int32)):
var nodes = @[fxGraph.add("buffer", bufArgsOf(frame))]
# Erode only the alpha plane: in gbrap the color planes are 0=G, 1=B,
# 2=R, so threshold0..2=0 freezes them and only plane 3 (alpha) erodes.
# Each pass pulls the matte edge inward by 1px.
nodes.add fxGraph.add("format", "pix_fmts=gbrap")
for _ in 0 ..< n:
nodes.add fxGraph.add("erosion", "threshold0=0:threshold1=0:threshold2=0")
nodes.add fxGraph.add("format", &"pix_fmts={$AVPixelFormat(frame.format)}")
nodes.add fxGraph.add("buffersink")
fxGraph.linkNodes(nodes).configure()
of actAberration:
# Fake chromatic aberration: slide each color channel by its own offset,
# so the gaps show up as colored fringing. Via rgba so an overlay layer's
# alpha rides through unshifted.
let edge = (if effect.abWrap: "wrap" else: "smear")
runFx(fxId(actAberration, frame,
i0 = effect.abRh.int32, i1 = effect.abRv.int32,
i2 = effect.abGh.int32, i3 = effect.abGv.int32,
f0 = effect.abBh.float32, f1 = effect.abBv.float32,
col = (if effect.abWrap: 1'u32 else: 0'u32))):
let bufferSrc = fxGraph.add("buffer", bufArgsOf(frame))
let toRgba = fxGraph.add("format", "pix_fmts=rgba")
let shift = fxGraph.add("rgbashift",
&"rh={effect.abRh}:rv={effect.abRv}:gh={effect.abGh}:gv={effect.abGv}" &
&":bh={effect.abBh}:bv={effect.abBv}:edge={edge}")
let toOrig = fxGraph.add("format", &"pix_fmts={$AVPixelFormat(frame.format)}")
let bufferSink = fxGraph.add("buffersink")
fxGraph.linkNodes(bufferSrc, toRgba, shift, toOrig, bufferSink).configure()
of actMask, actMaskPoly:
# Shape the alpha from a cached matte via alphamerge (cheap per frame).
let matte = cachedMatte(frame, effect)
frame = alphamergeOnto(frame, matte)
if not isOverlay:
# Base layer: nothing below to reveal, so flatten the masked-out area
# over the timeline background.
frame = overBg(frame)
of actPixelate:
# Mosaic censor. Clamp the block to the frame so pixelize can't reject a
# block larger than the plane; 1x1 blocks are a no-op.
let w = min(int(round(sample(effect, effect.pixWKf, effect.pixWKt))), frame.width)
let h = min(int(round(sample(effect, effect.pixHKf, effect.pixHKt))), frame.height)
if w > 1 or h > 1:
runFx(fxId(actPixelate, frame, i0 = w.int32, i1 = h.int32)):
let bufferSrc = fxGraph.add("buffer", bufArgsOf(frame))
let filt = fxGraph.add("pixelize", &"width={w}:height={h}")
let bufferSink = fxGraph.add("buffersink")
fxGraph.linkNodes(bufferSrc, filt, bufferSink).configure()
of actConfetti:
# In the layer's own format so an overlay's alpha survives; fillRect only
# writes yuv420p and rgba, so convert anything else first.
let want = (if hasAlpha(AVPixelFormat(frame.format)): AV_PIX_FMT_RGBA
else: AV_PIX_FMT_YUV420P)
let conv = frame.reformat(want, ctx = lazyCtx(fxConvCtx))
if conv != frame:
av_frame_free(addr frame)
frame = conv
# Required, not defensive: the pre-effects frame is cached by clone, so
# this buffer is shared and an in-place draw would compound into it.
if av_frame_make_writable(frame) < 0:
error "Could not make frame writable for confetti"
drawConfetti(frame, effect, local, fps)
of actBurn, actText:
# Timed from the start of the clip or generator layer it draws on, and
# drawn in the frame's own format where burn can; otherwise a picture
# with transparency (a generator's clear canvas) goes to RGBA, keeping
# the subtitles' coverage.
let fmt = AVPixelFormat(frame.format)
let want = (if canBurn(fmt): fmt elif hasAlpha(fmt): AV_PIX_FMT_RGBA
else: AV_PIX_FMT_YUV420P)
let conv = frame.reformat(want, ctx = lazyCtx(fxConvCtx))
if conv != frame:
av_frame_free(addr frame)
frame = conv
# The pre-effects frame is cached by clone, so its buffer is shared.
if av_frame_make_writable(frame) < 0:
error "Could not make frame writable for burn"
if effect.kind == actBurn and effect.burnFile.len == 0:
if src == nil: error "burn: a layer without media has no subtitles of its own"
burner.burn(frame, effect, srcSecs, src[])
else:
burner.burn(frame, effect, local.float / fps)
of actConfine, actConfinePoly:
# Set/clear the region the following adjustment effects are masked to.
confineActive = not effect.mReset
confineEffect = effect
return frame
proc pickDecoder(ss: SrcState, src: ptr string, obj: VideoFrame): DecState =
## The decoder that reaches `obj.index` with the least decoding among those
## not yet used this timeline frame. When all are, opens another.
var bestCost = high(int)
for d in ss.decoders:
if d.usedAt != frameNo:
let pos = d.loopBase + d.frameIndex
let cost =
if d.held != nil and obj.index >= d.lastReqIndex and obj.index <= pos: 0
elif obj.index >= pos: obj.index - pos
else: high(int) div 2 # behind it: a backward seek
if cost < bestCost:
bestCost = cost
result = d
if result == nil:
if ss.decoders.len < maxDecoders:
let cn = (try: av.open(src[]) except IOError as e: error e.msg)
let decoder = initDecoder(cn.video[0].codecpar)
decoder.thread_type = FF_THREAD_FRAME or FF_THREAD_SLICE
result = newDecState(cn, decoder, true)
ss.decoders.add result
debug &"Decoder {ss.decoders.len} for {src[]}"
else:
result = ss.decoders[0]
result.usedAt = frameNo
proc decodeRawFrame(obj: VideoFrame): (ptr AVFrame, bool) =
## Decode one clip's frame at its native resolution, maintaining per-source
## seek state. Still images decode once and return clones. Caller owns the
## returned frame.
if obj.gen: # generator overlay: a clear canvas for its action to paint
return (makeClear(tl.res[0].cint, tl.res[1].cint), true)
if obj.src == nil: # synthesized background base (audio-only `add`)
return (av_frame_clone(nullFrame), true)
let ss = srcs[obj.src]
if ss.isStill:
if ss.still == nil:
let imgStream = myCache.cns[obj.src].video[0]
var scratch = av_frame_clone(nullFrame)
var got: ptr AVFrame = nil
for decodedFrame in myCache.cns[obj.src].flushDecode(imgStream.index.cint,
ss.decoders[0].decoder, scratch):
got = av_frame_clone(decodedFrame)
break
av_frame_free(addr scratch)
if got == nil:
got = av_frame_clone(nullFrame)
ss.still = got
return (av_frame_clone(ss.still), true)
let cacheKey = (obj.src, obj.index)
if cacheKey in decodedCache:
# Another layer at this same timeline frame already decoded this exact
# source frame. Reuse it.
return (av_frame_clone(decodedCache[cacheKey]), true)
let st = ss.pickDecoder(obj.src, obj)
# `loop` makes the source restart when it runs out: requests past the source
# end map back to its start. `loopBase` is the frames consumed by completed
# loops, so the local decode `target` (and the decoder's frameIndex) stay in
# one loop's coordinate space while obj.index keeps climbing.
let looping = firstIsLoop(obj.effects)
var loopBase = st.loopBase
var target = obj.index - loopBase
if target < 0:
# The request precedes the completed loops: a looping overlay restarted
# (e.g. follow-base=0 in a later section). Re-anchor at zero; linear
# timelines hit this too, not just nonlinear ones.
loopBase = 0
target = obj.index
if obj.index >= st.lastReqIndex and obj.index <= loopBase + st.frameIndex and
st.held != nil:
st.lastReqIndex = obj.index
return (av_frame_clone(st.held), true)
var frame = av_frame_clone(nullFrame)
let myStream: ptr AVStream = st.cn.video[0]
var frameIndex = st.frameIndex
var seekThreshold = st.seekThreshold
var seekFrame = st.seekFrame
var hasSeekFrame = st.hasSeekFrame
var seekWant = -1 # a seek must land at or before this frame
var seekMargin = 0
if frameIndex > target:
# Seek to the largest observed keyframe <= target. A backward seek only
# ever targets a frame we have already decoded past, so every keyframe up
# to here has been observed (upfront `keyframeIndices` is unreliable:
# sparsely-cued containers can report just a single keyframe).
# observedKeyframes is kept strictly ascending, so upperBound-1 is the
# floor; frame 0 is always a valid seek point.
# bwdif needs the frame before the target, so for an interlaced source
# land on a keyframe before that one too.
let want = if st.interlaced: max(0, target - 1) else: target
let idx = upperBound(ss.observedKeyframes, want) - 1
let seekTarget = if idx >= 0: ss.observedKeyframes[idx] else: 0
if seekTarget < 0 or seekTarget > target:
let indexInfo = if ss.hasKfIndex: &"{ss.kfFrames.len} indexed" else: "no index"
error &"Cannot seek backward: no suitable keyframe found " &
&"(frameIndex: {frameIndex}, target: {target}, seekTarget: {seekTarget}, {indexInfo})"
debug &"Seek backward: from {frameIndex} to keyframe {seekTarget} (need frame {target})"
st.cn.seek(
videoFrameToTimestamp(seekTarget, ss.frameRate, myStream.time_base) +
st.cn.startPts(myStream), stream = myStream)
avcodec_flush_buffers(st.decoder)
st.resetDeint()
st.lastSeekTarget = seekTarget
# The threshold guards the frames past an earlier seek-ahead; behind
# them now, a later far request would decode all the way up to it.
seekThreshold = min(seekThreshold, seekTarget)
seekWant = want
frameIndex = min(seekTarget, target - 1)
var didDecode = false
# The clip going out of a transition can run past its file's last frame,
# as at a cut between two whole files. Premiere repeats that frame when a
# cut has no handle media, so hold it rather than drop to the background.
let holdPastEnd = obj.win >= 0 and not obj.incoming
var lastGood: ptr AVFrame = nil
var fromHeld = false
# Catching up to a far target decodes frames only to drop them. Those no
# other frame references needn't be decoded at all, until close enough to
# the target that it and the frame before it, which bwdif needs, come
# whole. The lead also covers frames a frame-threaded decoder already has.
var exactAll = ss.frameRate.num <= 0 or ss.frameRate.den <= 0
template aimSkip() =
let lead = if exactAll: 0 else: max(2, int(ceil(0.3 * ss.frameRate.float)))
st.exactFrom =
if exactAll or target <= lead: AV_NOPTS_VALUE
else: videoFrameToTimestamp(target - lead, ss.frameRate,
myStream.time_base) + st.cn.startPts(myStream)
aimSkip()
while frameIndex < target:
if target - frameIndex > ss.kfInterval and frameIndex > seekThreshold:
if st.lastSeekTarget != target:
seekThreshold = frameIndex + (ss.kfInterval div 2)
seekFrame = frameIndex
hasSeekFrame = true
debug &"Seek: {frameIndex} -> {target}"
st.cn.seek(
videoFrameToTimestamp(
if st.interlaced: max(0, target - 1) else: target,
ss.frameRate, myStream.time_base) +
st.cn.startPts(myStream), stream = myStream)
avcodec_flush_buffers(st.decoder)
st.resetDeint()
st.lastSeekTarget = target
seekWant = if st.interlaced: max(0, target - 1) else: target
seekMargin = 0
let foundFrame = st.nextFrame(myStream, frame)
let index =
if not foundFrame: -1
else: int(round((frame.time(myStream.time_base) -
float(st.cn.startPts(myStream) * myStream.time_base)) *
ss.frameRate.float))
if seekWant >= 0 and (not foundFrame or index > seekWant) and
seekWant >= seekMargin:
# MPEG-TS seeks by estimate and can land past the wanted frame, or
# past the last keyframe, which would lose the frames between, so
# back off further, doubling, until it doesn't. Even a seek to its
# start time can skip the first keyframe; one before it can't.
seekMargin = (if seekMargin == 0: max(ss.kfInterval, 1) else: seekMargin * 2)
let at = seekWant - seekMargin
st.cn.seek(videoFrameToTimestamp(at, ss.frameRate, myStream.time_base) +
st.cn.startPts(myStream), stream = myStream)
avcodec_flush_buffers(st.decoder)
st.resetDeint()
frameIndex = max(at, 0) - 1
continue
seekWant = -1
if foundFrame:
frameIndex = index
if frame.pict_type == AV_PICTURE_TYPE_I and
frameIndex > ss.observedKeyframes[^1]:
ss.observedKeyframes.add frameIndex
if foundFrame and holdPastEnd:
if lastGood != nil: av_frame_free(addr lastGood)
lastGood = av_frame_clone(frame)
if foundFrame:
didDecode = true
if hasSeekFrame:
let framesAvoided = frameIndex - seekFrame
debug &"Seek landed at frame {frameIndex}, avoided decoding {framesAvoided} frames"
framesSaved += framesAvoided
hasSeekFrame = false
elif not exactAll and st.decoder.skip_frame != AVDISCARD_DEFAULT:
# The stream ended while still skipping, so its last frames may be
# among the skipped. Which frame is last decides where a loop wraps,
# what is held past the end, and whether a later request is behind
# the decoder, so decode the tail again in full.
exactAll = true
aimSkip()
st.decoder.skip_frame = AVDISCARD_DEFAULT
let want = max(frameIndex, 0)
let idx = upperBound(ss.observedKeyframes, want) - 1
let seekTarget = if idx >= 0: ss.observedKeyframes[idx] else: 0
st.cn.seek(
videoFrameToTimestamp(seekTarget, ss.frameRate, myStream.time_base) +
st.cn.startPts(myStream), stream = myStream)
avcodec_flush_buffers(st.decoder)
st.resetDeint()
seekWant = want
seekMargin = 0
elif looping and frameIndex >= 0:
loopBase += frameIndex + 1
target = obj.index - loopBase
aimSkip()
st.cn.seek(0, stream = myStream)
avcodec_flush_buffers(st.decoder)
st.resetDeint()
st.lastSeekTarget = -1
frameIndex = -1
elif holdPastEnd and (lastGood != nil or st.held != nil):
av_frame_free(addr frame)
if lastGood != nil:
frame = lastGood
lastGood = nil
didDecode = true
else:
frame = av_frame_clone(st.held)
fromHeld = true
break
else:
didDecode = false
av_frame_free(addr frame)
frame = av_frame_clone(nullFrame)
break
if didDecode:
# Another layer sharing this (src, index) reuses it this timeline frame.
decodedCache[cacheKey] = av_frame_clone(frame)
if lastGood != nil: av_frame_free(addr lastGood)
st.frameIndex = frameIndex
st.seekThreshold = seekThreshold
st.seekFrame = seekFrame
st.hasSeekFrame = hasSeekFrame
st.loopBase = loopBase
st.lastReqIndex = obj.index
if didDecode:
# Hold the frame so a later monotonic-forward request
# that the overshooting decoder has already passed can reuse it (see the
# reuse check at the top) instead of seeking backward.
if st.held != nil:
var old = st.held
av_frame_free(addr old)
st.held = av_frame_clone(frame)
return (frame, didDecode or fromHeld)
proc decodeClipFrame(obj: VideoFrame): (ptr AVFrame, bool) =
## `decodeRawFrame`, after the clip's static rotation. The frames it keeps
## (still, held, shared) stay unrotated, since layers of one source can
## each have their own angle.
result = decodeRawFrame(obj)
if not result[1] or obj.gen or obj.src == nil: return
let deg = staticRotDeg(obj.effects)
if deg == 0.0'f32: return
let rad = deg * 3.14159265358979'f32 / 180.0'f32
var frame = result[0]
withFxGraph(fxId(actRotate, frame, f0 = rad)):
let bsrc = fxGraph.add("buffer", bufArgsOf(frame))
let filt = fxGraph.add("rotate", &"a={rad}:ow=rotw({rad}):oh=roth({rad}):c={bg}")
let bsink = fxGraph.add("buffersink")
fxGraph.linkNodes(bsrc, filt, bsink).configure()
fxGraph.move(frame)
av_frame_free(addr frame)
result[0] = fxGraph.pull()
# Output colorspace/range for overlays, from the encoder (stable). Declaring
# these on the base buffer keeps the composite yuv420p (not gbrp) and makes the
# overlay's rgb->yuv conversion match the base instead of washing out.
let ovColorspace =
if encoderCtx.colorspace.int in 1 .. 15: encoderCtx.colorspace.int
else: 1
let ovRange = (if encoderCtx.color_range.int == 2: 2 else: 1)
proc subpixelShift(src: ptr AVFrame; dx, dy: float32): ptr AVFrame =
## Bilinearly translate a packed-RGBA frame by (dx, dy) px, sampling
## out-of-bounds as transparent. Lets an animated overlay sit at a fractional
## pixel so a slow position ramp slides smoothly instead of stair-stepping.
let w = src.width.int
let h = src.height.int
let dst = av_frame_alloc()
if dst == nil: error "subpixelShift: could not allocate frame"
dst.format = src.format
dst.width = src.width
dst.height = src.height
dst.pts = src.pts
dst.time_base = src.time_base
if av_frame_get_buffer(dst, 32) < 0: error "subpixelShift: bad buffer"
# A column's left neighbor and weights are the same on every row. The
# weights are kept once a byte, not once a pixel, so the loop over a row's
# bytes below reads everything at a stride of one and can be vectorized.
if w == 0 or h == 0: return dst
var x0s = newSeq[int](w)
var wxSeq = newSeq[float32](w * 4)
var omwSeq = newSeq[float32](w * 4)
let wxs = cast[ptr UncheckedArray[float32]](addr wxSeq[0])
let omws = cast[ptr UncheckedArray[float32]](addr omwSeq[0])
for x in 0 ..< w:
let sxf = x.float32 - dx
let x0 = floor(sxf).int
let wx = sxf - x0.float32
x0s[x] = x0
for c in 0 ..< 4:
wxs[x * 4 + c] = wx
omws[x * 4 + c] = 1 - wx
# Columns xa ..< xb have both neighbors in the frame, the same `k`
# columns away. That is all but an edge column, short of a rounding quirk.
var xa = 0
while xa < w and (x0s[xa] < 0 or x0s[xa] + 1 >= w): inc xa
let k = (if xa < w: x0s[xa] - xa else: 0)
var xb = xa
while xb < w and x0s[xb] - xb == k and x0s[xb] + 1 < w: inc xb
for y in 0 ..< h:
let dRow = dst.planeRow(0, y)
let syf = y.float32 - dy
let y0 = floor(syf).int
let wy = syf - y0.float32
# The two source rows this one blends, nil where they're off the frame.
let top = (if y0 >= 0 and y0 < h: src.planeRow(0, y0) else: nil)
let bot = (if y0 + 1 >= 0 and y0 + 1 < h: src.planeRow(0, y0 + 1) else: nil)
template checked(x: int) =
for c in 0 ..< 4:
template px(row: ptr UncheckedArray[uint8], xx: int): float32 =
if row == nil or xx < 0 or xx >= w: 0.0'f32
else: row[xx * 4 + c].float32
let i = x * 4 + c
let t = px(top, x0s[x]) * omws[i] + px(top, x0s[x] + 1) * wxs[i]
let b = px(bot, x0s[x]) * omws[i] + px(bot, x0s[x] + 1) * wxs[i]
dRow[i] = uint8(clamp(t * (1 - wy) + b * wy + 0.5'f32, 0, 255))
if top == nil or bot == nil:
for x in 0 ..< w: checked(x)
else:
for x in 0 ..< xa: checked(x)
let left = cast[ptr UncheckedArray[uint8]](addr top[k * 4])
let leftBelow = cast[ptr UncheckedArray[uint8]](addr bot[k * 4])
for i in xa * 4 ..< xb * 4:
let t = left[i].float32 * omws[i] + left[i + 4].float32 * wxs[i]
let b = leftBelow[i].float32 * omws[i] + leftBelow[i + 4].float32 * wxs[i]
dRow[i] = uint8(clamp(t * (1 - wy) + b * wy + 0.5'f32, 0, 255))
for x in xb ..< w: checked(x)
return dst
proc overlayFrame(base, top: ptr AVFrame; x, y: float32;
scale: float32; takeBase: bool): ptr AVFrame =
## Composite `top` over `base` at (x, y), preserving the overlay's alpha.
## With `takeBase` the base's picture goes to the graph, which can then
## draw on it where it is, and `base` is left empty.
## (x, y) may be fractional: `overlay` places the integer part (it only does
## whole pixels) and a bilinear shift places the sub-pixel remainder, so a slow
## animated position slides smoothly.
let ix = floor(x).int
let iy = floor(y).int
let fx = x - ix.float32
let fy = y - iy.float32
let nw = max(2, int(top.width.float32 * scale))
let nh = max(2, int(top.height.float32 * scale))
let subpixel = abs(fx) >= 0.001'f32 or abs(fy) >= 0.001'f32
base.colorspace = cint(ovColorspace)
base.color_range = cint(ovRange)
var scaled: ptr AVFrame = nil
var upper = top
if subpixel:
# Scale to rgba up front (so alpha survives) and nudge it by the
# fractional remainder; the graph then overlays at the whole pixel.
scaled = top.reformat(AV_PIX_FMT_RGBA, nw.cint, nh.cint, lazyCtx(overlayCtx))
upper = subpixelShift(scaled, fx, fy)
# `overlay` emits once both inputs hold a frame of one timestamp, so a
# graph is kept from frame to frame and where the overlay sits is a
# command to it, not part of what it's built from.
withFxGraph(fxId(actPos, base, overlay = subpixel, i0 = upper.width,
i1 = upper.height, i2 = nw.int32, i3 = nh.int32, col = uint32(upper.format))):
# The two buffer sources must be nodes 0 (base) and 1 (top) and the sink
# last, to match pushIdx(0/1) and pull's nodes[^1].
let b0 = fxGraph.add("buffer",
bufArgsOf(base) & &":colorspace={ovColorspace}:range={ovRange}")
var upperOut = fxGraph.add("buffer", bufArgsOf(upper))
if not subpixel:
# Whole-pixel placement: scale in-graph (bicubic).
let topRgba = fxGraph.add("format", "pix_fmts=rgba")
let scl = fxGraph.add("scale", &"{nw}:{nh}:flags=bicubic")
fxGraph.link(upperOut, topRgba)
fxGraph.link(topRgba, scl)
upperOut = scl
let ov = fxGraph.add("overlay", "format=yuv420")
fxGraph.link(b0, ov, 0, 0)
fxGraph.link(upperOut, ov, 0, 1)
fxGraph.link(ov, fxGraph.add("buffersink"))
fxGraph.configure()
fxGraph.command("overlay", "x", $ix)
fxGraph.command("overlay", "y", $iy)
inc syncPts
base.pts = syncPts
upper.pts = syncPts
if takeBase: fxGraph.move(base, 0)
else: fxGraph.pushIdx(0, base)
fxGraph.pushIdx(1, upper)
result = fxGraph.pull()
result.pts = 0
if subpixel:
av_frame_free(addr upper)
if scaled != top: av_frame_free(addr scaled)
proc transformOverlay(top: ptr AVFrame; sx, sy, deg: float32): ptr AVFrame =
## `top` scaled and turned about its center, in a transparent frame just
## big enough to hold it.
let rad = deg.float * PI / 180
let sw = max(2, round(top.width.float * sx))
let sh = max(2, round(top.height.float * sy))
let bw = max(2, int(ceil(sw * abs(cos(rad)) + sh * abs(sin(rad)))))
let bh = max(2, int(ceil(sw * abs(sin(rad)) + sh * abs(cos(rad)))))
top.pts = 0
withFxGraph(fxId(actTurn, top, overlay = true, f0 = sx, f1 = sy, f2 = deg)):
let nodes = @[fxGraph.add("buffer", bufArgsOf(top)),
fxGraph.add("format", "pix_fmts=rgba"),
fxGraph.add("scale", &"{int(sw)}:{int(sh)}:flags=bicubic"),
fxGraph.add("rotate", &"a={rad}:ow={bw}:oh={bh}:c=black@0"),
fxGraph.add("buffersink")]
fxGraph.linkNodes(nodes).configure()
fxGraph.push(top)
result = fxGraph.pull()
proc scaleProxyFrame(f: ptr AVFrame): ptr AVFrame =
if scaleCtx == nil or f == nil or
(f.width == targetWidth and f.height == targetHeight):
return f
f.reformat(AVPixelFormat(f.format), targetWidth, targetHeight, scaleCtx)
proc finalizeFrame(f: ptr AVFrame; index: int64): ptr AVFrame =
var frame = f
if frame != nil and (frame.width <= 0 or frame.height <= 0):
debug &"Warning: Invalid frame at {index}tb, using fallback"
av_frame_free(addr frame)
frame =
if lastProcessedFrame != nil: av_frame_clone(lastProcessedFrame)
else: av_frame_clone(nullFrame)
if frame == nil:
error &"Failed to create fallback frame at {index}tb"
let scaled = scaleProxyFrame(frame)
if scaled != frame:
av_frame_free(addr frame)
frame = scaled
if args.videoHook != nil:
frame = args.videoHook(frame, args.videoHookData)
let reformatted = frame.reformat(pix_fmt, ctx = reformatCtx)
if reformatted != nil and reformatted != frame:
av_frame_free(addr frame)
frame = reformatted
frame.pts = index
frame.time_base = av_inv_q(tl.tb)
frame.duration = 1
result = frame
proc baseFrame(o: VideoFrame): ptr AVFrame =
## The bottom layer's picture: fit to the canvas over the background.
# Canvas-sized even with no frame decoded: the stand-in nullFrame is
# proxy-sized, and transitions blend it with canvas-sized frames.
var (acc, _) = decodeClipFrame(o)
if acc != nil and acc.width > 0 and acc.height > 0 and
(acc.width.int32, acc.height.int32) != tl.res:
let oldAcc = acc
acc = scaleWithPad(acc, tl.res[0], tl.res[1], tl.bg, solidTag, padCtx)
av_frame_free(addr oldAcc)
if acc != nil and acc.width > 0 and acc.height > 0:
acc = applyEffects(acc, o.effects, o.local, o.dur, src = o.src,
srcSecs = o.srcSecs)
acc
proc overlayObj(acc: ptr AVFrame, o: VideoFrame, takeAcc = false): ptr AVFrame =
## `o` composited over `acc` as a new frame, or nil when `o` has no frame
## for this position (its source ended, or hasn't started), so the base
## shows through rather than an opaque bg-filled fallback. `takeAcc` is
## for a caller done with `acc` once there is a new frame, as
## `overlayFrame` has it.
var (top, topDidDecode) = decodeClipFrame(o)
if not topDidDecode or top == nil or top.width <= 0 or top.height <= 0:
if top != nil: av_frame_free(addr top)
return nil
# Effects run at native size; overlayFrame scales (in full chroma).
top = applyEffects(top, o.effects, o.local, o.dur, isOverlay = true,
src = o.src, srcSecs = o.srcSecs)
# No explicit `pos`: fit the overlay to the canvas and center it, like
# the base layer (scaleWithPad), but let the padding stay transparent
# so only the image shows over the base.
var ox = o.x
var oy = o.y
var oscale = o.scale
if o.fit:
oscale = min(acc.width.float32 / top.width.float32,
acc.height.float32 / top.height.float32)
ox = float32((acc.width - int(top.width.float32 * oscale)) div 2)
oy = float32((acc.height - int(top.height.float32 * oscale)) div 2)
let (tw, th, tDeg) = scaleTurnOf(o.effects)
if tw != 1.0'f32 or th != 1.0'f32 or mod360(tDeg) != 0:
# Keep the overlay's center where it was placed. Turned at the
# size it's shown at, so it isn't enlarged afterwards.
let cx = ox + top.width.float32 * oscale / 2
let cy = oy + top.height.float32 * oscale / 2
let turned = transformOverlay(top, tw * oscale, th * oscale, tDeg)
av_frame_free(addr top)
top = turned
oscale = 1
ox = cx - top.width.float32 / 2
oy = cy - top.height.float32 / 2
result = overlayFrame(acc, top, ox, oy, oscale, takeAcc)
av_frame_free(addr top)
func placed(o: VideoFrame): bool =
## A clip with a `pos` goes where it says even with nothing under it,
## over the background, rather than filling the canvas as a base.
not o.fit
# Each layer's clips by start, and those started but not yet ended, so a
# frame looks only at the clips under it instead of every clip in the layer.
var byStart = newSeq[seq[int]](tl.v.len)
for li in 0 ..< tl.v.len:
# The sort's closure would copy the whole layer to capture it.
let layer {.cursor.} = tl.v[li]
for ci in 0 ..< layer.len: byStart[li].add ci
byStart[li].sort(proc(a, b: int): int = cmp(layer[a].start, layer[b].start))
var nextStart = newSeq[int](tl.v.len)
var started = newSeq[seq[int]](tl.v.len)
# Each layer's first transition window not yet over.
var nextWindow = newSeq[int](tl.v.len)
var speedMaps: Table[uint32, SpeedMap]
return (encoderCtx, outputStream, iterator(): (ptr AVFrame, int64) =
for index in startIndex ..< tl.len:
if stop != nil and stop[].load(): break
frameNo = index
objList = @[]
# The (src, index) decode cache is only valid within one timeline frame.
for _, f in decodedCache:
var df = f
av_frame_free(addr df)
decodedCache.clear()
dropIdleFxGraphs()
dropIdleMattes()
for layerIdx in 0 ..< tl.v.len:
# An alias: a loop variable here would copy the layer every frame, as
# the iterator keeps its locals in its closure.
template layer: untyped = tl.v[layerIdx]
while nextStart[layerIdx] < layer.len and
layer[byStart[layerIdx][nextStart[layerIdx]]].start <= index:
started[layerIdx].add byStart[layerIdx][nextStart[layerIdx]]
inc nextStart[layerIdx]
var live = 0
for k in 0 ..< started[layerIdx].len:
let ci = started[layerIdx][k]
if index < layer[ci].start + layer[ci].dur:
started[layerIdx][live] = ci
inc live
started[layerIdx].setLen(live)
# In layer order, as overlapping clips composite.
started[layerIdx].sort()
var win = -1
if layerIdx < tl.windows.len:
template windows: untyped = tl.windows[layerIdx]
if nextWindow[layerIdx] > 0 and
windows[nextWindow[layerIdx] - 1].start > index:
nextWindow[layerIdx] = 0 # a preview went back
while nextWindow[layerIdx] < windows.len and
windows[nextWindow[layerIdx]].start +
windows[nextWindow[layerIdx]].dur <= index:
inc nextWindow[layerIdx]
let wi = nextWindow[layerIdx]
if wi < windows.len and windows[wi].start <= index:
win = wi
let firstInLayer = objList.len
for ci in started[layerIdx]:
let obj = layer[ci]
let effectGroup = tl.effects[obj.effects]
if obj.effects notin speedMaps:
speedMaps[obj.effects] = initSpeedMap(effectGroup)
# The position in speed-scaled frames; a ramp moves through the
# clip's span unevenly.
let timelinePos =
if speedMaps[obj.effects].ramp:
obj.offset.float + obj.dur.float * speedMaps[obj.effects].mediaAt(
float(index - obj.start) / obj.dur.float)
else: float(obj.offset + index - obj.start)
var speed = 1.0
# Overlay placement comes from a `pos` action in the clip's effects
# (keeps Clip itself position-free); defaults to the canvas origin.
var ox, oy = 0.0'f32
var oscale = 1.0'f32
var hasPos = false
for effect in effectGroup:
if effect.kind == actSpeed:
speed *= effect.val
elif effect.kind == actPos:
hasPos = true
# Sample the placement ramps at this frame's progress, eased like
# the other animatable effects; static pos has 1-keyframe seqs.
# Kept as floats so overlayFrame can place at a sub-pixel offset.
let span = frameSpan(int(obj.dur), tl.tb.float)
let local = int(index - obj.start)
ox = effect.ramp(effect.pxKf, effect.pxKt, span).at(local)
oy = effect.ramp(effect.pyKf, effect.pyKt, span).at(local)
oscale = effect.ramp(effect.pscaleKf, effect.pscaleKt, span).at(local)
# A synthesized background base (nil src) has no source frame.
let sourceFramePos =
if obj.src == nil: 0
else:
let rate = myCache.cns[obj.src].video[0].avg_frame_rate
# 0/0 (no declared frame rate) would make the index NaN; map 1:1.
if rate.isValid:
int(round(timelinePos * rate.float / tl.tb.float))
else:
int(round(timelinePos))
var i = int(round(float(sourceFramePos) * speed))
if speedMaps[obj.effects].ramp and obj.src != nil:
# Rounding near a slow end can step past the clip's media.
let rate = myCache.cns[obj.src].video[0].avg_frame_rate
let fps = (if rate.isValid: rate.float / tl.tb.float else: 1.0)
let last = int(ceil(float(obj.offset + obj.dur) * speed * fps - 1e-3)) - 1
i = min(i, max(last, 0))
# nil src: the `-bg` canvas on the base track, a generator above it
# or where a `pos` places it.
objList.add VideoFrame(index: i, src: obj.src, effects: effectGroup,
gen: obj.src == nil and (layerIdx > 0 or hasPos),
local: int(index - obj.start), dur: int(obj.dur),
srcSecs: timelinePos * speed / tl.tb.float,
x: ox, y: oy, scale: oscale, fit: not hasPos, layer: layerIdx)
if win >= 0:
# A centered window holds the clip going out, then the one coming in.
let alignment = tl.windows[layerIdx][win].alignment
for k in firstInLayer ..< objList.len:
objList[k].win = win
objList[k].incoming = case alignment
of taStart: true
of taEnd: false
of taCenter:
if objList.len - firstInLayer == 1:
layer[started[layerIdx][0]].start >= tl.windows[layerIdx][win].start
else:
k > firstInLayer
# More than one active clip at this frame, or one in a transition =>
# composite layers (overlay / picture-in-picture / image overlays).
# objList is in track order, so objList[0] is the bottom (base) layer and
# later entries paint on top.
var inWindow = false
for o in objList:
if o.win >= 0: inWindow = true
if objList.len > 1 or inWindow or (objList.len == 1 and placed(objList[0])):
av_frame_free(addr frame)
var acc: ptr AVFrame = nil
var k = 0
while k < objList.len:
let o = objList[k]
if o.win < 0:
if acc == nil and not placed(o):
acc = baseFrame(o)
else:
if acc == nil:
acc = makeSolid(tl.res[0], tl.res[1], tl.bg, solidTag)
let newAcc = overlayObj(acc, o, takeAcc = true)
if newAcc != nil:
av_frame_free(addr acc)
acc = newAcc
inc k
else:
# A transition: the picture with the clip going out, blended into
# the one with the clip coming in, both over what's below.
var j = k
while j < objList.len and objList[j].layer == o.layer and
objList[j].win == o.win:
inc j
let isBase = acc == nil
let below =
if isBase: makeSolid(tl.res[0], tl.res[1], tl.bg, solidTag) else: acc
var fromF, toF: ptr AVFrame = nil
for m in k ..< j:
var f =
if isBase and not placed(objList[m]): baseFrame(objList[m])
else: overlayObj(below, objList[m])
if f == nil: f = av_frame_clone(below)
if objList[m].incoming:
if toF != nil: av_frame_free(addr toF)
toF = f
else:
if fromF != nil: av_frame_free(addr fromF)
fromF = f
if fromF == nil: fromF = av_frame_clone(below)
if toF == nil: toF = av_frame_clone(below)
let w = tl.windows[o.layer][o.win]
let local = index - w.start
# As Premiere: the first frame is all the outgoing picture.
let p = float32(local.float / w.dur.float)
let seed = uint32(w.start and 0xffffffff) xor (uint32(o.layer) * 2654435761'u32)
let dip: tuple[r, g, b: float32] = (bgRgb.red.float32, bgRgb.green.float32,
bgRgb.blue.float32)
let toRgb = lazyCtx(toRgbCtx)
let img = render(w.kind, fromF.toImg(toRgb), toF.toImg(toRgb),
below.toImg(toRgb), p, local.int, w.dur.int, seed, dip, w.easeIn,
w.easeOut)
acc = img.fromImg(fromF, lazyCtx(fromRgbCtx))
av_frame_free(addr fromF)
av_frame_free(addr toF)
var b = below
av_frame_free(addr b)
k = j
let scaledAcc = scaleProxyFrame(acc)
if scaledAcc != acc:
av_frame_free(addr acc)
acc = scaledAcc
frame = finalizeFrame(acc, index)
av_frame_free(addr lastProcessedFrame)
lastProcessedFrame = av_frame_clone(frame)
lastDecoded[1] = -1 # compositing bypasses the single-layer reuse cache
else:
if not isLinear:
# When there can be valid gaps in the timeline and no objects for this frame.
av_frame_free(addr frame)
frame = av_frame_clone(nullFrame)
else:
# Always start with a fresh frame to avoid reusing encoder-unref'd frames
av_frame_free(addr frame)
if pix_fmt == AV_PIX_FMT_RGB8 and lastProcessedFrame != nil:
frame = av_frame_clone(lastProcessedFrame)
else:
frame = av_frame_clone(nullFrame)
for obj in objList:
# Reuse the decoded frame from the previous timeline iteration when
# this frame maps to the same source frame.
if (obj.src, obj.index, staticRotDeg(obj.effects)) == lastDecoded and
lastProcessedFrame != nil:
av_frame_free(addr frame)
frame = av_frame_clone(lastProcessedFrame)
# The rotated pixels are reused without running the rotation
# graph, which the next new source frame needs again, so count
# it as used by this frame.
for e in fxGraphs.mitems:
if e.key.kind == actRotate:
e.usedAt = frameNo
else:
var (decoded, didDecode) = decodeClipFrame(obj)
if didDecode:
av_frame_free(addr frame)
frame = decoded
# decodeClipFrame returns native resolution; scale the final frame to
# the canvas (intermediate seek frames never reach here, so the resize
# costs one sws_scale rather than one per decoded frame).
if (frame.width.int32, frame.height.int32) != tl.res:
let oldFrame = frame
frame = scaleWithPad(frame, tl.res[0], tl.res[1], tl.bg, solidTag, padCtx)
av_frame_free(addr oldFrame)
else:
# No new frame decoded: keep the pre-initialized `frame` (nullFrame, or
# the last frame for RGB8 palette persistence) and drop the fallback.
av_frame_free(addr decoded)
# Effects take canvas pixels, so they run at the canvas size and the
# proxy scale comes after, as when compositing. A clip with no frame
# here leaves the proxy-sized nullFrame.
if objList.len > 0 and frame != nil and frame.width > 0 and frame.height > 0 and
(frame.width.int32, frame.height.int32) != tl.res:
let oldFrame = frame
frame = scaleWithPad(frame, tl.res[0], tl.res[1], tl.bg, solidTag, padCtx)
av_frame_free(addr oldFrame)
# Cache the pre-effects frame: effects are per-timeline-frame (animated
# via `local`) and would compound when a source frame repeats.
if objList.len > 0:
av_frame_free(addr lastProcessedFrame)
lastProcessedFrame = av_frame_clone(frame)
let o = objList[0]
lastDecoded = (o.src, o.index, staticRotDeg(o.effects))
if objList.len > 0 and frame != nil and frame.width > 0 and frame.height > 0:
frame = applyEffects(frame, objList[0].effects, objList[0].local,
objList[0].dur, src = objList[0].src, srcSecs = objList[0].srcSecs)
let scaledFrame = scaleProxyFrame(frame)
if scaledFrame != frame:
av_frame_free(addr frame)
frame = scaledFrame
frame = finalizeFrame(frame, index)
yield (frame, index)
for e in fxGraphs:
e.graph.cleanup()
fxGraphs.setLen(0)
burner.close()
for e in mattes.mitems:
av_frame_free(addr e.matte)
mattes.setLen(0)
sws_free_context(addr scaleCtx)
sws_free_context(addr padCtx)
sws_free_context(addr reformatCtx)
sws_free_context(addr zoomCtx)
sws_free_context(addr fxConvCtx)
sws_free_context(addr overlayCtx)
sws_free_context(addr toRgbCtx)
sws_free_context(addr fromRgbCtx)
av_frame_free(addr frame)
av_frame_free(addr lastProcessedFrame)
av_frame_free(addr nullFrame)
for _, f in decodedCache:
var df = f
av_frame_free(addr df)
if keep == nil: sources.close()
debug &"Total frames avoided decoding via seeks: {framesSaved}")