Effort free video editing!
type Piece* = tuple[at: int, start: int64]
## A stretch of a segment: its samples from index `at` on were read from
## the source starting at sample `start`.
func sourceSample*(pieces: openArray[Piece], at: int64): int64 =
## The source sample that sample `at` of a segment was read from, for a
## segment whose silences were dropped. `pieces` is ordered by `at`.
result = at
for p in pieces:
if p.at > at: break
result = p.start + (at - p.at)
func piecesFrom*(pieces: openArray[Piece], cut: int): seq[Piece] =
## The pieces of what is left of a segment once its first `cut` samples
## are taken off.
result = @[(at: 0, start: sourceSample(pieces, cut))]
for p in pieces:
if p.at > cut:
result.add (at: p.at - cut, start: p.start)
func windowPeak(samples: openArray[float32], start, win: int): float32 =
for i in start ..< min(start + win, samples.len):
result = max(result, abs(samples[i]))
func loudSamples*(samples: openArray[float32], win: int,
threshold: float32): int =
## How many samples lie in `win`-sized windows that peak at `threshold` or
## above.
var start = 0
while start < samples.len:
if windowPeak(samples, start, win) >= threshold:
result += min(win, samples.len - start)
start += win
func quietestCut*(samples: openArray[float32], win: int,
threshold: float32): int =
## The index to split `samples` at so the cut does the least harm to speech:
## the middle of the longest pause, or of the quietest stretch when nothing
## falls below `threshold`. The latest candidate wins a tie.
let n = samples.len div win
if n == 0:
return samples.len
var peaks = newSeq[float32](n)
for i in 0 ..< n:
peaks[i] = windowPeak(samples, i * win, win)
var pauseStart = 0
var pauseLen = 0
var run = 0
for i in 0 ..< n:
run = (if peaks[i] < threshold: run + 1 else: 0)
if run > 0 and run >= pauseLen:
pauseLen = run
pauseStart = i - run + 1
if pauseLen > 0:
# Mid-pause leaves each side some silence around its speech.
return pauseStart * win + pauseLen * win div 2
# Rank a window by its neighbors too, so a lone dip between two loud
# windows (a zero crossing, not a lull) loses to a wider one.
var best = 0
var bestScore = float32.high
for i in 0 ..< n:
let score = max(peaks[i], max(peaks[max(i - 1, 0)], peaks[min(i + 1, n - 1)]))
if score <= bestScore:
bestScore = score
best = i
best * win + win div 2
func gaveUp*(textLen: int, ms: int64): bool =
## Whether a cue of `textLen` bytes lasting `ms` holds too little text for
## its length to be speech that was followed: a model that loses its place
## closes the rest of a segment with one cue.
ms >= 10_000 and textLen.int64 * 1000 < ms * 2