Effort free video editing!
Keep effect and overlay graphs from frame to frame
WyattBluee0d4549de744
diff --git a/src/graph.nim b/src/graph.nimindex 60df6ce8..31ea42f6 100644--- a/src/graph.nim+++ b/src/graph.nim@@ -83,6 +83,13 @@ proc pushIdx*(graph: Graph; idx: int; frame: ptr AVFrame) =if ret < 0:error &"Error pushing frame to graph source {idx}: {ret}"+proc command*(graph: Graph, target, cmd, arg: string) =+ ## Set a runtime option on the filters named or typed `target`.+ let ret = avfilter_graph_send_command(graph.graph, target.cstring, cmd.cstring,+ arg.cstring, nil, 0, 0)+ if ret < 0:+ error &"Could not send '{cmd}' to filter '{target}': {ret}"+proc configure*(graph: Graph) =if graph.configured:returndiff --git a/src/render/video.nim b/src/render/video.nimindex 5907f449..0fc72a9f 100644--- a/src/render/video.nim+++ b/src/render/video.nim@@ -568,6 +568,29 @@ proc fillBox(frame: ptr AVFrame, x, y, w, h: int32, color: RGBColor) =u[col] = uvv[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.}@@ -1498,25 +1521,43 @@ proc makeNewVideoFrames*(output: var OutputContainer, tl: v3, args: mainArgs,template sample(e: Action, kf: seq[float32], kt: seq[KfTime]): float32 =e.ramp(kf, kt, frameSpan(clipDur, fps)).at(local)- # Run `frame` through the effect graph identified by `key`, which `build`- # makes as `withFxGraph` says. When the active `confine` covers this effect,- # run it on a copy and merge only the masked region back over the untouched- # frame.- template runFx(key: GraphKey, build: untyped) =- withFxGraph(key, build)+ # 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)- fxGraph.push(frame)- av_frame_free(addr frame)- let effected = fxGraph.pull()+ body+ let effected = frameframe = maskedMergeRegion(saved, effected, matte)av_frame_free(addr saved)av_frame_free(addr effected)else:- fxGraph.push(frame)- av_frame_free(addr frame)- frame = fxGraph.pull()+ body++ template throughFxGraph() =+ fxGraph.push(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@@ -1644,15 +1685,25 @@ proc makeNewVideoFrames*(output: var OutputContainer, tl: v3, args: mainArgs,of actBrightness:let b = sample(effect, effect.kf, effect.kt)if b != 0.0'f32:- let shift = b * 255.0'f32- runFx(fxId(actBrightness, frame, f0 = shift)):- 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={$AVPixelFormat(frame.format)}")- let bufferSink = fxGraph.add("buffersink")- fxGraph.linkNodes(bufferSrc, toRgb, lut, toOrig, bufferSink).configure()+ 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 andeffect.contrast == luvContrastId and@@ -1671,26 +1722,39 @@ proc makeNewVideoFrames*(output: var OutputContainer, tl: v3, args: mainArgs,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 > 1if isOverlay:- 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()+ 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:- runFx(fxId(actOpacity, frame, f0 = o)):- let bgR = (1.0'f32 - o) * float32(bgRgb.red)- let bgG = (1.0'f32 - o) * float32(bgRgb.green)- let bgB = (1.0'f32 - o) * float32(bgRgb.blue)- let bufferSrc = fxGraph.add("buffer", bufArgsOf(frame))- let toRgb = fxGraph.add("format", "pix_fmts=rgb24")- let lut = fxGraph.add("lutrgb",- &"r=val*{o}+{bgR}:g=val*{o}+{bgG}:b=val*{o}+{bgB}")- let toOrig = fxGraph.add("format",- &"pix_fmts={$AVPixelFormat(frame.format)}")- let bufferSink = fxGraph.add("buffersink")- fxGraph.linkNodes(bufferSrc, toRgb, lut, toOrig, bufferSink).configure()+ 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.k1let k2 = effect.k2@@ -2146,69 +2210,64 @@ proc makeNewVideoFrames*(output: var OutputContainer, tl: v3, args: mainArgs,dRow[x * 4 + c] = uint8(clamp(t * (1 - wy) + b * wy + 0.5'f32, 0, 255))return dst+ # Each pair of frames an overlay graph is given takes the next timestamp.+ var overlayPts = 0'i64+proc overlayFrame(base, top: ptr AVFrame; x, y: float32;scale: float32): ptr AVFrame =## Composite `top` over `base` at (x, y), preserving the overlay's alpha.## (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. Built per call because `overlay` is a- ## framesync filter (needs EOF on both inputs to emit).+ ## animated position slides smoothly.let ix = floor(x).intlet iy = floor(y).intlet fx = x - ix.float32let fy = y - iy.float32let 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'f32base.colorspace = cint(ovColorspace)base.color_range = cint(ovRange)- base.pts = 0- let baseArgs = bufArgsOf(base) & &":colorspace={ovColorspace}:range={ovRange}"- # 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 g = newGraph()- let b0 = g.add("buffer", baseArgs)-- if abs(fx) < 0.001'f32 and abs(fy) < 0.001'f32:- # Whole-pixel placement: scale in-graph (bicubic) and overlay.- top.pts = 0- let b1 = g.add("buffer", bufArgsOf(top))- let topRgba = g.add("format", "pix_fmts=rgba")- let scl = g.add("scale", &"{nw}:{nh}:flags=bicubic")- let ov = g.add("overlay", &"x={ix}:y={iy}:format=yuv420")- let sink = g.add("buffersink")- g.link(b1, topRgba, 0, 0)- g.link(topRgba, scl, 0, 0)- g.link(b0, ov, 0, 0)- g.link(scl, ov, 0, 1)- g.link(ov, sink, 0, 0)- g.configure()- g.pushIdx(0, base)- g.pushIdx(1, top)- g.flushIdx(0)- g.flushIdx(1)- result = g.pull()- g.cleanup()- else:- # Sub-pixel placement: scale to rgba up front (so alpha survives), nudge it by- # the fractional remainder, then overlay the prepared frame at the whole pixel.- let scaled = top.reformat(AV_PIX_FMT_RGBA, nw.cint, nh.cint,- lazyCtx(overlayCtx))- let shifted = subpixelShift(scaled, fx, fy)- shifted.pts = 0- let b1 = g.add("buffer", bufArgsOf(shifted))- let ov = g.add("overlay", &"x={ix}:y={iy}:format=yuv420")- let sink = g.add("buffersink")- g.link(b0, ov, 0, 0)- g.link(b1, ov, 0, 1)- g.link(ov, sink, 0, 0)- g.configure()- g.pushIdx(0, base)- g.pushIdx(1, shifted)- g.flushIdx(0)- g.flushIdx(1)- result = g.pull()- g.cleanup()- av_frame_free(addr shifted)+ 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 overlayPts+ base.pts = overlayPts+ upper.pts = overlayPts+ 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 =@@ -2220,14 +2279,15 @@ proc makeNewVideoFrames*(output: var OutputContainer, tl: v3, args: mainArgs,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- let g = newGraph()- let nodes = @[g.add("buffer", bufArgsOf(top)), g.add("format", "pix_fmts=rgba"),- g.add("scale", &"{int(sw)}:{int(sh)}:flags=bicubic"),- g.add("rotate", &"a={rad}:ow={bw}:oh={bh}:c=black@0"), g.add("buffersink")]- g.linkNodes(nodes).configure()- g.push(top)- result = g.pull()- g.cleanup()+ 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