Skip to content

Effort free video editing!

2.7 KB
Raw Blame
from std/math import floor, ceil
import ../[av, ffmpeg]
import ../lib/tinyre
import ../util/rational
from ../log import AutoEditorError, error

proc subtitle*(container: InputContainer, tb: AVRational, pattern: Re,
    stream: int16): (int32, seq[bool]) {.raises: [AutoEditorError].} =

  if stream < 0 or stream >= container.subtitle.len:
    return (stream, @[])

  let formatCtx = container.formatContext
  let s = container.subtitle[stream].index
  var codecCtx = initDecoder(formatCtx.streams[s].codecpar)
  defer: avcodec_free_context(addr codecCtx)
  let packet = av_packet_alloc()

  if packet == nil:
    error "Could not allocate packet"
  defer: av_packet_free(addr packet)

  let subtitleStream: AVStream = container.subtitle[stream][]

  # Rewind so a shared container can be re-read for additional streams. Ignore
  # failure: sidecar subtitle demuxers (e.g. srt) can't seek, but those
  # containers are freshly opened and already at the start.
  discard av_seek_frame(formatCtx, -1, 0, AVSEEK_FLAG_BACKWARD)
  # Cues are a sliver of the file: let the demuxer skip the video and audio.
  let levels = container.setActiveStream(s)
  defer: container.restoreDiscards(levels)

  var length = 0
  var spans: seq[(int, int)] = @[]
  var subtitle: AVSubtitle
  while av_read_frame(formatCtx, packet) >= 0:
    defer: av_packet_unref(packet)

    if packet.stream_index == s:
      # Duration 0 means unknown; an empty span can't mark a frame anyway.
      if not (packet.pts == AV_NOPTS_VALUE or packet.duration <= 0):
        let
          startFloat = float((packet.pts - container.startPts(addr subtitleStream)) *
            subtitleStream.time_base)
          durFloat = float(packet.duration * subtitleStream.time_base)
          # A subtitle is active for any frame it overlaps, so snap outward:
          # floor the start, ceil the end. round() could clip a frame the
          # subtitle actually touches. Edit lists and hand-written srt/ass can
          # start a cue before 0.
          start = max(0, floor(startFloat * tb).int)
          `end` = ceil((startFloat + durFloat) * tb).int

        var gotSubtitle: cint = 0
        let ret = avcodec_decode_subtitle2(codecCtx, addr subtitle,
          addr gotSubtitle, packet)

        if ret >= 0 and gotSubtitle != 0:
          defer: avsubtitle_free(addr subtitle)

          length = max(length, `end`)
          for i in 0..<subtitle.num_rects:
            let rect = subtitle.rects[i]
            if rect.`type` == SUBTITLE_ASS and rect.ass != nil:
              var assText: string = $rect.ass
              if match(assText.dialogue, pattern).len > 0:
                spans.add((start, `end`))

  var val = newSeq[bool](length)
  for span in spans:
    for i in span[0] ..< span[1]:
      val[i] = true

  return (-1, val)