Skip to content

Effort free video editing!

Rechunk loudnorm output without copying the buffer per piece

WyattBlueed80cb2738e1
diff --git a/src/render/audio.nim b/src/render/audio.nim
index acabb4d3..49785cb7 100644
--- a/src/render/audio.nim
+++ b/src/render/audio.nim
@@ -1252,7 +1252,7 @@ proc makeAudioFrames*(fmt: AVSampleFormat, tl: v3, frameSize: int, layerIndices:
# Wrap an interleaved int16 chunk as an S16P frame, resample to the output
# format, and return the resulting (frame, index) pairs. Advances pts state.
- proc emitChunk(chunk: seq[int16]): seq[(ptr AVFrame, int64)] =
+ proc emitChunk(chunk: openArray[int16]): seq[(ptr AVFrame, int64)] =
let chunkFrames = chunk.len div targetChannels
if chunkFrames == 0:
return @[]
@@ -1280,15 +1280,12 @@ proc makeAudioFrames*(fmt: AVSampleFormat, tl: v3, frameSize: int, layerIndices:
# EBU's loudnorm may emit a slightly different sample count than the timeline;
# cap the apply pass to `totalSamples` so output duration is preserved.
var ebuEmitted = 0
- proc emitCapped(chunk: seq[int16]): seq[(ptr AVFrame, int64)] =
+ proc emitCapped(chunk: openArray[int16]): seq[(ptr AVFrame, int64)] =
if ebuEmitted >= totalSamples:
return @[]
- var c = chunk
- let avail = totalSamples - ebuEmitted
- if c.len div targetChannels > avail:
- c.setLen(avail * targetChannels)
- ebuEmitted += c.len div targetChannels
- return emitChunk(c)
+ let n = min(chunk.len, (totalSamples - ebuEmitted) * targetChannels)
+ ebuEmitted += n div targetChannels
+ return emitChunk(chunk.toOpenArray(0, n - 1))
# loudnorm's output frames track its internal 100ms block size, not the
# encoder's frame_size. Fixed-frame-size encoders (e.g. AAC) reject any
@@ -1297,15 +1294,20 @@ proc makeAudioFrames*(fmt: AVSampleFormat, tl: v3, frameSize: int, layerIndices:
var rechunkBuf: seq[int16]
proc drainRechunk(final: bool): seq[(ptr AVFrame, int64)] =
let full = frameSize * targetChannels
- while rechunkBuf.len >= full or (final and rechunkBuf.len > 0):
+ var off = 0
+ while rechunkBuf.len - off >= full or (final and rechunkBuf.len > off):
if ebuEmitted >= totalSamples:
- rechunkBuf = @[]
+ off = rechunkBuf.len
break
- let take = min(full, rechunkBuf.len)
- let piece = rechunkBuf[0 ..< take]
- rechunkBuf = (if take < rechunkBuf.len: rechunkBuf[take .. ^1] else: @[])
- for fr in emitCapped(piece):
+ let take = min(full, rechunkBuf.len - off)
+ for fr in emitCapped(rechunkBuf.toOpenArray(off, off + take - 1)):
result.add fr
+ off += take
+ # The unsent rest moves down once, not after every piece.
+ let keep = rechunkBuf.len - off
+ if off > 0 and keep > 0:
+ moveMem(addr rechunkBuf[0], addr rechunkBuf[off], keep * sizeof(int16))
+ rechunkBuf.setLen(keep)
return iterator(): (ptr AVFrame, int64) =
defer: