Skip to content

Effort free video editing!

30.1 KB
Raw Blame
## The `burn` action: libass draws a subtitle file, on a generator layer's
## clear canvas (`add:burn:talk.srt`) or over a section's picture, styled as
## the file says (SRT gets FFmpeg's default header) but for what the action
## overrides: font file, size, and colors. A frame gets the subtitles that show
## at its time in the layer or clip.

import std/[strformat, strutils, unicode]
import ../[action, ffmpeg, log]
when defined(libass):
  import std/[hashes, math, os, tables]
  import ../[av, libass]
  import ../util/rational
  proc c_strdup(s: cstring): cstring {.importc: "strdup", header: "<string.h>".}

type
  Mask = object
    ## An image's coverage summed over each block of a subsampling, times its
    ## opacity, out of `full`.
    sw, sh, w, full: int
    cov: seq[int]

  Drawn = object
    ## An image from a renderer's last frame, and its masks.
    w, h, stride, x, y: cint
    color: uint32
    bitmap: seq[uint8]
    masks: seq[Mask]

  SubBurner* = object
    when defined(libass):
      lib: ptr ASS_Library
      renderers: Table[(cint, cint), ptr ASS_Renderer] # by frame size
      # A subtitle shows for many frames, so its masks are kept while its
      # images stay the same.
      drawn: Table[pointer, seq[Drawn]]
      tracks: Table[string, ptr ASS_Track] # by the burn action
      families: Table[string, string] # by font file
      attached: int
      own: Table[string, string]

var fallbackFont*: string

func assColor(c: uint32): string =
  ## 0xRRGGBBAA as ASS writes it: &HAABBGGRR, its alpha counting transparency.
  let (r, g, b, a) = (c shr 24, (c shr 16) and 0xff, (c shr 8) and 0xff, c and 0xff)
  "&H" & toHex(int(((255 - a) shl 24) or (b shl 16) or (g shl 8) or r), 8)

proc u16(data: string, at: int): int =
  if at < 0 or at + 2 > data.len: raise newException(ValueError, "truncated font")
  (data[at].ord shl 8) or data[at + 1].ord

proc u32(data: string, at: int): int = (data.u16(at) shl 16) or data.u16(at + 2)

proc faceOffsets(data: string): seq[int] =
  ## Where each face's table directory starts: a collection has several.
  if data.startsWith("ttcf"):
    for i in 0 ..< min(data.u32(8), 4096): result.add data.u32(12 + 4 * i)
  else:
    result.add 0

proc fontName(data: string, face, id: int): string =
  ## Name `id` in the `name` table of the face at `face`; "" if it has none.
  var table = -1
  for i in 0 ..< data.u16(face + 4):
    let rec = face + 12 + 16 * i
    if rec + 4 <= data.len and data[rec ..< rec + 4] == "name":
      table = data.u32(rec + 8)
  if table < 0: return ""
  let strings = table + data.u16(table + 4)
  # English before another language's, as a font can name itself in several,
  # and a Unicode encoding before Mac Roman, the one Mac encoding read here.
  var best = (rank: 99, text: "")
  for i in 0 ..< data.u16(table + 2):
    let rec = table + 6 + 12 * i
    if data.u16(rec + 6) != id: continue
    let (encoding, language) = (data.u16(rec + 2), data.u16(rec + 4))
    let rank = case data.u16(rec)
      of 3: (if (language and 0x3ff) == 9: 0 else: 3)
      of 0: 1
      of 1: (if encoding == 0 and language == 0: 2 else: 99)
      else: 99
    let (len, at) = (data.u16(rec + 8), strings + data.u16(rec + 10))
    if rank >= best.rank or at + len > data.len: continue
    var text = ""
    if rank == 2:
      text = data[at ..< at + len]
    else:
      var k = at
      while k + 1 < at + len:
        text.add Rune(data.u16(k)).toUTF8
        k += 2
    best = (rank, text)
  best.text

proc fontFamily*(data: string): string =
  ## The family name in a TrueType/OpenType font's `name` table (the first
  ## face of a collection), as libass matches fonts by; "" if it has none.
  try:
    fontName(data, faceOffsets(data)[0], 1)
  except ValueError:
    ""

proc fontFaces*(data: string): seq[string] =
  ## Each face's style, as `face=` takes it: "Bold", "Condensed Medium".
  try:
    for at in faceOffsets(data):
      let style = fontName(data, at, 17)
      result.add (if style.len > 0: style else: fontName(data, at, 2))
  except ValueError:
    result = @[]

proc findFace*(data, face: string): int =
  ## The index of the face `face` names, by its place in the file from 0, its
  ## style, its full name, or its PostScript name; -1 if the font has none.
  try:
    let faces = faceOffsets(data)
    if face.allCharsInSet(Digits):
      let index = (if face.len <= 4: parseInt(face) else: faces.len)
      return (if index < faces.len: index else: -1)
    for i, at in faces:
      for id in [17, 2, 4, 6]:
        if cmpIgnoreCase(fontName(data, at, id), face) == 0: return i
  except ValueError:
    discard
  -1

proc be(v: uint32, bytes: int): string =
  for i in countdown(bytes - 1, 0): result.add chr((v shr (8 * i)) and 0xff)

proc be(v: int, bytes: int): string = be(uint32(v), bytes)

proc extractFace*(data: string, face: int, family: string): string =
  ## The face at `face` as a font file of its own, the one face of `family`.
  ## libass picks among a family's faces by weight and slant alone, so one
  ## that differs in width, or shares both with another, is only reached as
  ## a family of its own. "" if the font can't be read.
  try:
    let at = faceOffsets(data)[face]
    let count = data.u16(at + 4)
    var names = ""
    var strings = ""
    for id in [1, 2, 4, 6]:
      let text = (if id == 2: "Regular" else: family)
      var utf16 = ""
      for r in text.runes: utf16.add be(min(r.int, 0xffff), 2)
      names.add be(3, 2) & be(1, 2) & be(0x409, 2) & be(id, 2) &
        be(utf16.len, 2) & be(strings.len, 2)
      strings.add utf16
    let name = be(0, 2) & be(4, 2) & be(6 + names.len, 2) & names & strings
    var dir = data[at ..< at + 12]
    var body = ""
    let start = 12 + 16 * count
    for i in 0 ..< count:
      let rec = at + 12 + 16 * i
      let tag = data[rec ..< rec + 4]
      let (offset, len) = (data.u32(rec + 8), data.u32(rec + 12))
      if tag != "name" and offset + len > data.len: return ""
      let table = (if tag == "name": name else: data[offset ..< offset + len])
      let padded = table & repeat('\0', (4 - table.len mod 4) mod 4)
      var sum = data[rec + 4 ..< rec + 8]
      if tag == "name":
        var total = 0'u32
        for k in countup(0, padded.len - 4, 4):
          total += uint32(padded.u16(k)) shl 16 or uint32(padded.u16(k + 2))
        sum = be(total, 4)
      dir.add tag & sum & be(start + body.len, 4) & be(table.len, 4)
      body.add padded
    dir & body
  except ValueError:
    ""

func assText(text: string): string =
  for c in text:
    case c
    of '\n': result.add "\\N"
    of '\\': result.add "\\\u2060"
    of '{', '}': result.add "\\" & c
    else: result.add c

func eventText(text: string, ass: bool): string =
  if ass:
    for c in text:
      if c == '\n': result.add "\\N" else: result.add c
  else:
    result = assText(text)

func cellLines(text: string, ass: bool): seq[seq[string]] =
  if not ass:
    for line in text.splitLines():
      result.add @[]
      for ch in line.runes: result[^1].add assText($ch)
  else:
    result = @[newSeq[string]()]
    var tags = ""
    var i = 0
    while i < text.len:
      let close = (if text[i] == '{': text.find('}', i + 1) else: -1)
      if close >= 0:
        tags &= text[i .. close].replace("\n", "\\N")
        i = close + 1
      elif text[i] == '\n' or
          text[i] == '\\' and i + 1 < text.len and text[i + 1] in {'N', 'n'}:
        result.add @[]
        tags = ""
        i += (if text[i] == '\n': 1 else: 2)
      elif text[i] == '\\' and i + 1 < text.len and text[i + 1] == 'h':
        result[^1].add tags & "\\h"
        i += 2
      else:
        var n = 1
        while n < text.runeLenAt(i) and i + n < text.len and text[i + n].ord in 0x80..0xbf:
          inc n
        result[^1].add tags & text[i ..< i + n]
        i += n

func tagLang*(tag: string): string =
  ## The ISO 639-1 code libass's line breaking knows for a stream's language
  ## tag, which containers store as ISO 639-2; "" for other languages.
  case tag
  of "en", "eng": "en"
  of "de", "ger", "deu": "de"
  of "es", "spa": "es"
  of "fr", "fre", "fra": "fr"
  of "ru", "rus": "ru"
  of "ja", "jpn": "ja"
  of "ko", "kor": "ko"
  of "zh", "chi", "zho": "zh"
  else: ""

type Script = enum kana, hangul, han

func scripts(text: string): set[Script] =
  for r in text.runes:
    let c = r.int32
    if c in 0x3040'i32 .. 0x30FF'i32: result.incl kana
    elif c in 0xAC00'i32 .. 0xD7AF'i32 or c in 0x1100'i32 .. 0x11FF'i32 or
        c in 0x3130'i32 .. 0x318F'i32: result.incl hangul
    elif c in 0x4E00'i32 .. 0x9FFF'i32 or c in 0x3400'i32 .. 0x4DBF'i32: result.incl han

func scriptLang(seen: set[Script]): string =
  # Japanese nearly always has kana and Korean hangul, so Han alone is Chinese.
  if kana in seen: "ja" elif hangul in seen: "ko" elif han in seen: "zh" else: ""

func textLang*(text: string): string =
  ## The ISO 639-1 code a text's writing system implies, for untagged
  ## subtitles: "ja", "ko", or "zh", else "".
  scriptLang(scripts(text))

func vertAlignParts(align: uint8): tuple[h, v: string] =
  if align notin 1'u8 .. 9'u8:
    return ("center", "middle")
  let name = alignNames[align]
  let h = (if "left" in name: "left" elif "right" in name: "right" else: "center")
  let v = (if "top" in name: "top" elif "bottom" in name: "bottom" else: "middle")
  (h, v)

func verticalEvents(text: string, ass: bool, cell, w, h: float, align: uint8): string =
  let lines = cellLines(text, ass)
  var maxChars = 0
  for line in lines: maxChars = max(maxChars, line.len)
  let totalW = lines.len.float * cell
  let totalH = maxChars.float * cell
  let (mx, my) = (w * 0.05, h * 0.05)
  let (ha, va) = vertAlignParts(align)
  let x0 = case ha
    of "left": mx
    of "right": w - mx - totalW
    else: (w - totalW) / 2
  let y0 = case va
    of "top": my
    of "bottom": h - my - totalH
    else: (h - totalH) / 2
  for i, line in lines:
    for j, glyph in line:
      let cx = x0 + totalW - cell * (i.float + 1) + cell / 2
      let cy = y0 + cell * j.float + cell / 2
      result &= &"Dialogue: 0,0:00:00.00,9:59:59.99,Default,,0,0,0,," &
        &"{{\\an5\\pos({cx:.2f},{cy:.2f})}}{glyph}\n"

func textScript(text: Action, w, h: cint): string =
  let size = h.float * 0.08
  let outline = max(1.0, h.float * 0.002)
  let (mx, my) = (int(w.float * 0.05), int(h.float * 0.05))
  let events =
    if text.burnVertical:
      let fontsize = (if text.burnSize > 0: text.burnSize.float * h.float / 100 else: size)
      verticalEvents(text.burnFile, text.burnAss, fontsize * 1.15, w.float, h.float, text.burnAlign)
    else:
      &"Dialogue: 0,0:00:00.00,9:59:59.99,Default,,0,0,0,," &
        &"{eventText(text.burnFile, text.burnAss)}\n"
  &"""[Script Info]
ScriptType: v4.00+
PlayResX: {w}
PlayResY: {h}
ScaledBorderAndShadow: yes
WrapStyle: 2

[V4+ Styles]
Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
Style: Default,Arial,{size:.2f},&H00FFFFFF,&H00FFFFFF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,{outline:.2f},0,5,{mx},{mx},{my},1

[Events]
Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
{events}"""

proc canBurn*(format: AVPixelFormat): bool =
  ## Whether `burn` draws on `format` as it is: little-endian RGB, YUV, or
  ## gray of 8 to 16 bits, with alpha only where nothing is subsampled.
  let d = av_pix_fmt_desc_get(format)
  if d == nil or d.nb_components == 0: return false
  const known = AV_PIX_FMT_FLAG_PLANAR or AV_PIX_FMT_FLAG_RGB or AV_PIX_FMT_FLAG_ALPHA
  if (d.flags and not known) != 0: return false
  if (d.flags and AV_PIX_FMT_FLAG_ALPHA) != 0 and
      (d.log2_chroma_w != 0 or d.log2_chroma_h != 0):
    return false
  let bytes = (d.comp[0].depth + 7) div 8
  for c in d.comp[0 ..< d.nb_components.int]:
    if c.depth notin 8 .. 16 or (c.depth + 7) div 8 != bytes or c.offset mod bytes != 0:
      return false
    # In a sample's high or low bits, never between.
    if c.shift != 0 and (c.shift + c.depth) mod 8 != 0: return false
  true

when defined(libass):
  func playResY(track: ptr ASS_Track): float =
    ## The height a script's coordinates (and font sizes) are in, as libass
    ## takes it: PlayResY, else from PlayResX, else 288.
    let (x, y) = (track.PlayResX, track.PlayResY)
    if y > 0: y.float
    elif x == 1280: 1024
    elif x > 0: max(1, x * 3 div 4).float
    else: 288

  proc quiet(level: cint, fmt: ConstCString, args: VaList, data: pointer) {.cdecl.} =
    # FFmpeg's own logging is off, and libass would print to stderr.
    discard

  proc library(b: var SubBurner): ptr ASS_Library =
    if b.lib == nil:
      b.lib = ass_library_init()
      if b.lib == nil: error "Could not initialize libass"
      ass_set_message_cb(b.lib, quiet, nil)
      ass_set_extract_fonts(b.lib, 1)
    b.lib

  proc family(b: var SubBurner, font, face, name: string): string =
    ## The family libass finds `font` by once it holds its data: the font's
    ## own, or one made for `face` alone.
    let key = font & "\0" & face
    if key notin b.families:
      let data = try: readFile(font) except IOError:
        error &"{name}: can't read the font {font}"
      var family = fontFamily(data)
      if family.len == 0: error &"{name}: {font} has no font family name"
      if face.len == 0:
        ass_add_font(b.library, extractFilename(font).cstring, data.cstring, data.len.cint)
      else:
        let index = findFace(data, face)
        if index < 0:
          var has: seq[string]
          for i, style in fontFaces(data): has.add &"{i} {style}"
          error &"{name}: {font} has no face {face}; it has " & has.join(", ")
        family = &"{family} face {index} {toHex(hash(font) and 0xffffff, 6)}"
        let one = extractFace(data, index, family)
        if one.len == 0: error &"{name}: can't read face {face} of {font}"
        ass_add_font(b.library, (extractFilename(font) & "#" & $index).cstring,
          one.cstring, one.len.cint)
      b.families[key] = family
    b.families[key]

  proc renderer(b: var SubBurner, w, h: cint): ptr ASS_Renderer =
    # One for each size, since resizing a renderer empties its caches.
    result = b.renderers.getOrDefault((w, h))
    if result == nil:
      result = ass_renderer_init(b.library)
      if result == nil: error "Could not initialize libass's renderer"
      ass_set_frame_size(result, w, h)
      ass_set_storage_size(result, w, h)
      let family = if fallbackFont.len > 0: b.family(fallbackFont, "", "--font") else: ""
      ass_set_fonts(result, nil, (if family.len > 0: family.cstring else: nil),
        ASS_FONTPROVIDER_AUTODETECT, nil, 1)
      b.renderers[(w, h)] = result

  const fontMimes = ["font/ttf", "font/otf", "font/sfnt", "font/woff",
    "font/woff2", "application/font-sfnt", "application/font-woff",
    "application/x-truetype-font", "application/vnd.ms-opentype",
    "application/x-font-ttf"]

  proc fontName(st: ptr AVStream): cstring =
    ## The file name of a font attached to a container, such as a Matroska
    ## file's for its ASS track; nil for any other stream.
    if st.codecpar.codec_type != AVMEDIA_TYPE_ATTACHMENT: return nil
    let mime = av_dict_get(st.metadata, "mimetype", nil, 1)
    if mime == nil or toLowerAscii($mime.value) notin fontMimes: return nil
    let name = av_dict_get(st.metadata, "filename", nil, 1)
    if name != nil: name.value else: nil

  proc fileTrack(b: var SubBurner, path: string): ptr ASS_Track =
    ## The first text subtitle stream in `path`, with the fonts attached to it.
    var container = try: av.open(path)
      except IOError: error &"burn: can't read the subtitles {path}"
    defer: container.close()
    var st: ptr AVStream = nil
    for s in container.subtitle:
      let d = avcodec_descriptor_get(s.codecpar.codec_id)
      if d != nil and (d.props and AV_CODEC_PROP_TEXT_SUB) != 0:
        st = s
        break
    if st == nil: error &"burn: {path} has no text subtitles"
    let fmt = container.formatContext
    for i in 0 ..< fmt.nb_streams.int:
      let a = fmt.streams[i]
      let name = fontName(a)
      if name != nil:
        ass_add_font(b.library, name, cast[cstring](a.codecpar.extradata),
          a.codecpar.extradata_size)
        inc b.attached

    let codec = avcodec_find_decoder(st.codecpar.codec_id)
    if codec == nil:
      error &"burn: can't decode {avcodec_get_name(st.codecpar.codec_id)} subtitles"
    var dec = avcodec_alloc_context3(codec)
    if dec == nil: error "Could not allocate decoder ctx"
    defer: avcodec_free_context(addr dec)
    if avcodec_parameters_to_context(dec, st.codecpar) < 0:
      error &"burn: can't decode the subtitles in {path}"
    # What the decoder times each subtitle by; it's otherwise left unset.
    dec.pkt_timebase = st.time_base
    if avcodec_open2(dec, codec, nil) < 0:
      error &"burn: can't decode the subtitles in {path}"

    result = ass_new_track(b.library)
    if result == nil: error "Could not create a libass track"
    # Native ASS keeps the line breaking it was written for.
    if st.codecpar.codec_id != ID_ASS:
      discard ass_track_set_feature(result, ASS_FEATURE_WRAP_UNICODE, 1)
    if dec.subtitle_header != nil:
      ass_process_codec_private(result, cast[cstring](dec.subtitle_header),
        dec.subtitle_header_size)
    let packet = container.packet
    var seen: set[Script]
    # Cues are a sliver of the file: let the demuxer skip the video and audio.
    container.setActiveStream(st.index)
    while av_read_frame(fmt, packet) >= 0:
      defer: av_packet_unref(packet)
      if packet.stream_index != st.index: continue
      var sub: AVSubtitle
      var got: cint = 0
      if avcodec_decode_subtitle2(dec, addr sub, addr got, packet) >= 0 and got != 0:
        let start = av_rescale_q(sub.pts - fmt.start_time.max(0),
          AVRational(num: 1, den: AV_TIME_BASE), AVRational(num: 1, den: 1000))
        for i in 0 ..< sub.num_rects.int:
          let line = sub.rects[i].ass
          if line == nil: break
          seen = seen + scripts($line)
          ass_process_chunk(result, line, line.len.cint, start, sub.end_display_time.clonglong)
        avsubtitle_free(addr sub)

    # The language steers the Unicode line breaking: in Chinese, Japanese, and
    # Korean, characters ambiguous between scripts break like ideographs. The
    # stream's tag names it; an .srt has none, so its writing system stands in.
    if st.codecpar.codec_id != ID_ASS and result.Language == nil:
      let tag = av_dict_get(st.metadata, "language", nil, 0)
      var lang = (if tag == nil: "" else: tagLang($tag.value))
      if lang.len == 0: lang = scriptLang(seen)
      if lang.len > 0: result.Language = c_strdup(lang.cstring)

  proc ownSubtitles(b: var SubBurner, media: string): string =
    if media notin b.own:
      var path = ""
      try:
        var container = av.open(media)
        defer: container.close()
        for s in container.subtitle:
          let d = avcodec_descriptor_get(s.codecpar.codec_id)
          if d != nil and (d.props and AV_CODEC_PROP_TEXT_SUB) != 0:
            path = media
            break
      except IOError: discard
      if path.len == 0:
        for ext in ["srt", "ass"]:
          if fileExists(media.changeFileExt(ext)):
            path = media.changeFileExt(ext)
            break
      if path.len == 0: error &"burn: {media} has no subtitles"
      b.own[media] = path
    b.own[media]

  proc track(b: var SubBurner, burn: Action, w, h: cint, media: string): ptr ASS_Track =
    # A text's script is written for the frame's size.
    let key = if burn.kind == actText: &"{burn} {w}x{h}"
      elif burn.burnFile.len == 0: &"{burn} {media}"
      else: $burn
    result = b.tracks.getOrDefault(key)
    if result != nil: return
    # Elsewhere the system finds a font when none is given.
    when not (defined(macosx) or defined(windows)):
      let attached = b.attached
    if burn.kind == actText:
      let script = textScript(burn, w, h)
      result = ass_read_memory(b.library, script.cstring, script.len.csize_t, nil)
      if result == nil: error "text: libass can't read its script"
    else:
      result = b.fileTrack(if burn.burnFile.len > 0: burn.burnFile else: b.ownSubtitles(media))
    b.tracks[key] = result

    let name = if burn.kind == actText: "text" else: "burn"
    when not (defined(macosx) or defined(windows)):
      if burn.burnFont.len == 0 and fallbackFont.len == 0 and b.attached == attached:
        error &"{name}: no font to draw with, give one with font= or --font"
    var style: seq[string]
    if burn.burnFont.len > 0:
      style.add "FontName=" & b.family(burn.burnFont, burn.burnFace, name)
    elif burn.burnFace.len > 0:
      error &"{name}: face needs a font file, give one with font="
    if burn.burnWeight > 0:
      style.add &"Bold={burn.burnWeight}"
    if burn.burnSize > 0:
      # A percent of the frame, in the script's own coordinates.
      style.add &"Fontsize={burn.burnSize.float * result.playResY / 100:.2f}"
    if bpColor in burn.burnSet:
      style.add "PrimaryColour=" & assColor(burn.burnColors[bpColor])
    if bpOutline in burn.burnSet:
      style.add "OutlineColour=" & assColor(burn.burnColors[bpOutline])
    if bpBg in burn.burnSet:
      # libass's own border style: one box behind each subtitle, the outline
      # kept.
      style.add "BorderStyle=4"
      style.add "BackColour=" & assColor(burn.burnColors[bpBg])
    if burn.burnAlign in 1'u8 .. 9'u8:
      const ssa: array[1 .. 9, int] = [1, 2, 3, 9, 10, 11, 5, 6, 7]
      style.add &"Alignment={ssa[burn.burnAlign]}"
    if style.len > 0:
      let list = allocCStringArray(style)
      defer: deallocCStringArray(list)
      ass_set_style_overrides(b.lib, list)
      ass_process_force_style(result)
      # The library keeps them, and would give them to the next script it reads.
      ass_set_style_overrides(b.lib, nil)

  proc render(b: var SubBurner, burn: Action, w, h: cint, secs: float,
      media = ""): tuple[track: ptr ASS_Track, images: ptr ASS_Image,
      drawn: ptr seq[Drawn], change: cint] =
    result.track = b.track(burn, w, h, media)
    let r = b.renderer(w, h)
    result.images = ass_render_frame(r, result.track,
      clonglong(round(secs * 1000)), addr result.change)
    result.drawn = addr b.drawn.mgetOrPut(r, @[])

  proc colorIn(frame: ptr AVFrame, d: ptr AVPixFmtDescriptor, track: ptr ASS_Track,
      color: uint32): array[3, float] =
    ## An image's color as `frame`'s components hold it, from 0 to 1.
    let rgb = [float(color shr 24), float((color shr 16) and 0xff),
      float((color shr 8) and 0xff)]
    for i in 0 .. 2: result[i] = rgb[i] / 255
    if (d.flags and AV_PIX_FMT_FLAG_RGB) != 0: return

    # A script's YCbCr Matrix names the YUV its colors were picked against,
    # as FFmpeg's subtitles filter takes it.
    var (csp, range) = (frame.colorspace.int, frame.color_range.int)
    case track.YCbCrMatrix
    of YCBCR_NONE: discard
    of YCBCR_SMPTE240M_TV, YCBCR_SMPTE240M_PC: csp = 7 # AVCOL_SPC_SMPTE240M
    of YCBCR_FCC_TV, YCBCR_FCC_PC: csp = 4 # AVCOL_SPC_FCC
    of YCBCR_BT709_TV, YCBCR_BT709_PC: csp = 1 # AVCOL_SPC_BT709
    else: csp = 6 # AVCOL_SPC_SMPTE170M
    case track.YCbCrMatrix
    of YCBCR_NONE: discard
    of YCBCR_BT601_PC, YCBCR_BT709_PC, YCBCR_SMPTE240M_PC, YCBCR_FCC_PC: range = 2
    else: range = 1
    if range == 0: # AVCOL_RANGE_UNSPECIFIED
      range = (if startsWith($AVPixelFormat(frame.format), "yuvj"): 2 else: 1)
    let luma = av_csp_luma_coeffs_from_avcsp(AVColorSpace(csp))
    let (kr, kb) =
      if luma == nil or luma.cr.den == 0: (0.299, 0.114)
      else: (luma.cr.float, luma.cb.float)
    let (r, g, b) = (result[0], result[1], result[2])
    let y = kr * r + (1 - kr - kb) * g + kb * b
    result = [y, (b - y) / (2 * (1 - kb)), (r - y) / (2 * (1 - kr))]
    if range == 1: # AVCOL_RANGE_MPEG
      result[0] = result[0] * 219 / 255 + 16 / 255
      for i in 1 .. 2: result[i] = result[i] * 224 / 255 + 128 / 255
    else:
      for i in 1 .. 2: result[i] += 0.5

  proc at(frame: ptr AVFrame, c: AVComponentDescriptor, x, y: int): pointer =
    addr frame.planeRow(c.plane.int, y)[x * c.step.int + c.offset.int]

  proc load(p: pointer, wide: bool): int =
    if wide: cast[ptr uint16](p)[].int else: cast[ptr uint8](p)[].int

  proc store(p: pointer, n: int, wide: bool) =
    if wide: cast[ptr uint16](p)[] = n.uint16 else: cast[ptr uint8](p)[] = n.uint8

  proc mask(masks: var seq[Mask], img: ptr ASS_Image, x0, y0, x1, y1, opacity,
      sw, sh: int): ptr Mask =
    ## `img`'s coverage over the clipped box, times `opacity`, at a plane's
    ## subsampling. The chroma components share theirs.
    for m in masks.mitems:
      if (m.sw, m.sh) == (sw, sh): return addr m
    let (cx0, cy0) = (x0 shr sw, y0 shr sh)
    var m = Mask(sw: sw, sh: sh, w: ((x1 - 1) shr sw) - cx0 + 1,
      full: (255 * 255) shl (sw + sh))
    m.cov = newSeq[int](m.w * (((y1 - 1) shr sh) - cy0 + 1))
    for y in y0 ..< y1:
      let row = (y - img.dst_y) * img.stride - img.dst_x
      let at = ((y shr sh) - cy0) * m.w - cx0
      for x in x0 ..< x1:
        m.cov[at + (x shr sw)] += img.bitmap[row + x].int
    for v in m.cov.mitems: v *= opacity
    masks.add m
    addr masks[^1]

  proc blend(frame: ptr AVFrame, img: ptr ASS_Image, track: ptr ASS_Track,
      masks: var seq[Mask]) =
    ## Draws one of libass's images, a color through a coverage mask, over
    ## `frame`: on transparency, "over" so the frame's alpha takes its coverage.
    let opacity = 255 - int(img.color and 0xff)
    let (x0, y0) = (max(img.dst_x.int, 0), max(img.dst_y.int, 0))
    let x1 = min(int(img.dst_x + img.w), frame.width.int)
    let y1 = min(int(img.dst_y + img.h), frame.height.int)
    if opacity == 0 or x0 >= x1 or y0 >= y1: return
    let d = av_pix_fmt_desc_get(AVPixelFormat(frame.format))
    let hasAlpha = (d.flags and AV_PIX_FMT_FLAG_ALPHA) != 0
    let colors = d.nb_components.int - ord(hasAlpha)
    let wide = d.comp[0].depth > 8
    let target = colorIn(frame, d, track, img.color)

    let alpha = d.comp[d.nb_components.int - 1]
    # The colors first, each over the alpha as it was.
    for i in 0 ..< colors:
      let chroma = i > 0 and (d.flags and AV_PIX_FMT_FLAG_RGB) == 0
      let (sw, sh) = (if chroma: (d.log2_chroma_w.int, d.log2_chroma_h.int) else: (0, 0))
      let m = masks.mask(img, x0, y0, x1, y1, opacity, sw, sh)
      let full = m.full
      let c = d.comp[i]
      let top = (1 shl (c.depth + c.shift)) - 1
      let t = int(round(target[i] * top.float))
      for cy in (y0 shr sh) .. ((y1 - 1) shr sh):
        let row = (cy - (y0 shr sh)) * m.w - (x0 shr sw)
        for cx in (x0 shr sw) .. ((x1 - 1) shr sw):
          let a = m.cov[row + cx]
          if a == 0: continue
          let p = frame.at(c, cx, cy)
          let v = load(p, wide)
          if hasAlpha:
            let a = a / full
            let da = load(frame.at(alpha, cx, cy), wide) / top
            let oa = a + da * (1 - a)
            store(p, int(round((target[i] * a + v / top * da * (1 - a)) / oa * top.float)),
              wide)
          else:
            # Without alpha it's a mix toward the color, which needs no floats.
            let m = (t - v) * a
            store(p, v + (if m >= 0: (m + full div 2) div full else: -((full div 2 - m) div full)),
              wide)
    if hasAlpha:
      let m = masks.mask(img, x0, y0, x1, y1, opacity, 0, 0)
      let top = (1 shl (alpha.depth + alpha.shift)) - 1
      for y in y0 ..< y1:
        let row = (y - y0) * m.w - x0
        for x in x0 ..< x1:
          let a = m.cov[row + x]
          if a > 0:
            let p = frame.at(alpha, x, y)
            let a = a / m.full
            store(p, int(round((a + load(p, wide) / top * (1 - a)) * top.float)), wide)

proc burn*(b: var SubBurner, frame: ptr AVFrame, burn: Action, secs: float,
    media = "") =
  ## Draws `burn`'s subtitles as they show `secs` into its layer or clip onto
  ## `frame`, which must be writable and in a format `canBurn` takes.
  when defined(libass):
    let (track, images, drawn, change) =
      b.render(burn, frame.width, frame.height, secs, media)
    var (img, i) = (images, 0)
    while img != nil:
      if i == drawn[].len: drawn[].add Drawn()
      let n = (if img.h > 0 and img.w > 0: int((img.h - 1) * img.stride + img.w) else: 0)
      # libass makes some bitmaps, like a box's, anew each frame, so a change
      # it reports can still leave an image the same.
      template same(e: Drawn): bool =
        (e.w, e.h, e.stride, e.x, e.y, e.color) ==
          (img.w, img.h, img.stride, img.dst_x, img.dst_y, img.color) and
          (n == 0 or equalMem(addr e.bitmap[0], img.bitmap, n))
      if change != 0 and not same(drawn[][i]):
        drawn[][i] = Drawn(w: img.w, h: img.h, stride: img.stride, x: img.dst_x,
          y: img.dst_y, color: img.color, bitmap: newSeq[uint8](n))
        if n > 0: copyMem(addr drawn[][i].bitmap[0], img.bitmap, n)
      blend(frame, img, track, drawn[][i].masks)
      (img, i) = (img.next, i + 1)
    drawn[].setLen i
  else:
    error "burn and text need auto-editor built with libass"

proc close*(b: var SubBurner) =
  when defined(libass):
    for t in b.tracks.values: ass_free_track(t)
    b.tracks.clear()
    for r in b.renderers.values: ass_renderer_done(r)
    b.renderers.clear()
    b.families.clear()
    b.attached = 0
    b.own.clear()
    if b.lib != nil:
      ass_library_done(b.lib)
      b.lib = nil

proc textBounds*(text: Action, w, h: cint): tuple[x, y, w, h: int] =
  ## Where `text` draws on a `w` by `h` frame.
  when defined(libass):
    var b = SubBurner()
    defer: b.close()
    var (x0, y0, x1, y1) = (w.int, h.int, -1, -1)
    var img = b.render(text, w, h, 0).images
    while img != nil:
      if (img.color and 0xff) != 0xff:
        for y in max(img.dst_y.int, 0) ..< min(int(img.dst_y + img.h), h.int):
          let row = (y - img.dst_y) * img.stride - img.dst_x
          for x in max(img.dst_x.int, 0) ..< min(int(img.dst_x + img.w), w.int):
            if img.bitmap[row + x] != 0:
              (x0, y0, x1, y1) = (min(x0, x), min(y0, y), max(x1, x), max(y1, y))
      img = img.next
    if x1 >= 0: (x0, y0, x1 - x0 + 1, y1 - y0 + 1) else: (0, 0, 0, 0)
  else:
    error "text needs auto-editor built with libass"

proc attachedFonts*(path: string): seq[string] =
  when defined(libass):
    var container = try: av.open(path) except IOError: return
    defer: container.close()
    let fmt = container.formatContext
    for i in 0 ..< fmt.nb_streams.int:
      let name = fontName(fmt.streams[i])
      if name != nil: result.add $name