Skip to content

Effort free video editing!

11.2 KB
Raw Blame
import std/[json, sets, strformat, strutils, tables]
import ../[av, cli, ffmpeg, log, media]
import ../lib/[aspect, lang]
import ../util/rational
import ./help

func genericTrack(lang: Lang, bitrate: int64): string =
  if bitrate != 0:
    result.add &"     - bitrate: {bitrate}\n"
  if lang != ['u', 'n', 'd', '\0']:
    result.add &"     - lang: {lang}\n"

func bt709(val: int): string =
  if val == 1:
    return "1 (bt709)"
  return $val

func fourccToString(fourcc: uint32): string =
  var buf: array[5, char]
  buf[0] = char(fourcc and 0xFF)
  buf[1] = char((fourcc shr 8) and 0xFF)
  buf[2] = char((fourcc shr 16) and 0xFF)
  buf[3] = char((fourcc shr 24) and 0xFF)
  buf[4] = '\0'
  return $cast[cstring](addr buf[0])

proc yamlInfo(fileInfo: MediaInfo): string =
  template line(s: string) =
    result.add s
    result.add '\n'

  let tb = recommendedTimebase(fileInfo)
  line &"{fileInfo.path}:\n - recommendedTimebase: {tb.num}/{tb.den}"

  if fileInfo.v.len > 0:
    line " - video:"
  for track, v in fileInfo.v:
    let (ratioWidth, ratioHeight) = aspectRatio(v.width, v.height, v.sar.num, v.sar.den)
    var sar: AVRational
    discard av_reduce(addr sar.num, addr sar.den, v.sar.num, v.sar.den, high(int32))

    line &"   - track {track}:"
    line &"     - codec: {$avcodec_get_name(v.codecId)}"
    line &"     - fps: {v.avg_rate}"
    line &"     - resolution: {v.width}x{v.height}"
    line &"     - aspect ratio: {ratioWidth}:{ratioHeight}"
    line &"     - pixel aspect ratio: {sar}"
    if v.duration != 0.0:
      line &"     - duration: {v.duration}"
    line &"     - pix fmt: {v.pix_fmt}"

    if v.color_range == 1:
      line "     - color range: 1 (tv)"
    elif v.color_range == 2:
      line "     - color range: 2 (pc)"
    elif v.color_range != 0:
      line &"     - color range: {v.color_range}"

    if v.color_space != 2:
      line &"     - color space: {v.color_space.bt709}"
    if v.color_primaries != 2:
      line &"     - color primaries: {v.color_primaries.bt709}"
    if v.color_transfer != 2:
      line &"     - color transfer: {v.color_transfer.bt709}"
    line &"     - timebase: {v.timebase}"
    result.add genericTrack(v.lang, v.bitrate)


  if fileInfo.a.len > 0:
    line " - audio:"
  for track, a in fileInfo.a:
    line &"   - track {track}:"
    line &"     - codec: {$avcodec_get_name(a.codecId)}"
    line &"     - layout: {a.layout}"
    line &"     - samplerate: {a.samplerate}"
    if a.duration != 0.0:
      line &"     - duration: {a.duration}"
    result.add genericTrack(a.lang, a.bitrate)

  if fileInfo.s.len > 0:
    line " - subtitle:"
  for track, s in fileInfo.s:
    line &"   - track {track}:"
    line &"     - codec: {$avcodec_get_name(s.codecId)}"
    result.add genericTrack(s.lang, 0)

  if fileInfo.d.len > 0:
    line " - data:"
  for track, d in fileInfo.d:
    line &"   - track {track}:"
    line &"     - codec: {$avcodec_get_name(d.codecId)} ({fourccToString(d.tag)})"
    line &"     - timecode: {d.timecode}"

  if fileInfo.i.len > 0:
    line " - image:"
  for track, i in fileInfo.i:
    let (ratioWidth, ratioHeight) = aspectRatio(i.width, i.height, i.sar.num, i.sar.den)
    var sar: AVRational
    discard av_reduce(addr sar.num, addr sar.den, i.sar.num, i.sar.den, high(int32))

    line &"   - track {track}:"
    line &"     - codec: {$avcodec_get_name(i.codecId)}"
    line &"     - resolution: {i.width}x{i.height}"
    line &"     - aspect ratio: {ratioWidth}:{ratioHeight}"
    line &"     - pixel aspect ratio: {sar}"
    line &"     - pix fmt: {i.pix_fmt}"

    if i.color_range == 1:
      line "     - color range: 1 (tv)"
    elif i.color_range == 2:
      line "     - color range: 2 (pc)"
    elif i.color_range != 0:
      line &"     - color range: {i.color_range}"

    if i.color_space != 2:
      line &"     - color space: {i.color_space.bt709}"
    if i.color_primaries != 2:
      line &"     - color primaries: {i.color_primaries.bt709}"
    if i.color_transfer != 2:
      line &"     - color transfer: {i.color_transfer.bt709}"
    result.add genericTrack(i.lang, i.bitrate)

  line " - container:"
  if fileInfo.duration != 0.0:
    line &"   - duration: {fileInfo.duration}"
  line &"   - bitrate: {fileInfo.bitrate}"


proc getJsonInfo(fileInfo: MediaInfo): JsonNode =
  var varr, aarr, sarr, iarr: seq[JsonNode] = @[]
  let tb = recommendedTimebase(fileInfo)

  for v in fileInfo.v:
    let (ratioWidth, ratioHeight) = aspectRatio(v.width, v.height, v.sar.num, v.sar.den)
    var sar: AVRational
    discard av_reduce(addr sar.num, addr sar.den, v.sar.num, v.sar.den, high(int32))
    varr.add( %* {
      "codec": $avcodec_get_name(v.codecId),
      "fps": $v.avg_rate,
      "resolution": [v.width, v.height],
      "aspect_ratio": [ratioWidth, ratioHeight],
      "pixel_aspect_ratio": $sar,
      "duration": v.duration,
      "pix_fmt": $v.pix_fmt,
      "color_range": v.color_range,
      "color_space": v.color_space,
      "color_primaries": v.color_primaries,
      "color_transfer": v.color_transfer,
      "timebase": $v.timebase,
      "bitrate": v.bitrate,
      "lang": v.lang
    })

  for a in fileInfo.a:
    # `decodable` is this build's answer, not the format's: a container can name
    # a codec nothing here can read (Apple's `apac` Spatial Audio track), and a
    # caller planning work per stream needs to know before it asks.
    aarr.add( %* {"codec": $avcodec_get_name(a.codecId), "layout": a.layout,
        "samplerate": a.sampleRate, "duration": a.duration,
        "bitrate": a.bitrate, "lang": a.lang, "decodable": canDecode(a.codecId)})

  for s in fileInfo.s:
    sarr.add( %* s)

  for i in fileInfo.i:
    let (ratioWidth, ratioHeight) = aspectRatio(i.width, i.height, i.sar.num, i.sar.den)
    var sar: AVRational
    discard av_reduce(addr sar.num, addr sar.den, i.sar.num, i.sar.den, high(int32))
    iarr.add( %* {
      "codec": $avcodec_get_name(i.codecId),
      "resolution": [i.width, i.height],
      "aspect_ratio": [ratioWidth, ratioHeight],
      "pixel_aspect_ratio": $sar,
      "pix_fmt": $i.pix_fmt,
      "color_range": i.color_range,
      "color_space": i.color_space,
      "color_primaries": i.color_primaries,
      "color_transfer": i.color_transfer,
      "lang": i.lang
    })

  result = %* {
    "type": "media",
    "recommendedTimebase": $tb.num & "/" & $tb.den,
    "video": varr,
    "audio": aarr,
    "subtitle": sarr,
    "image": iarr,
    "container": {
      "duration": fileInfo.duration,
      "bitrate": fileInfo.bitrate
    }
  }


type CodecListKind = enum clkEncoders, clkDecoders, clkCodecs

var hwDeviceCache: Table[AVHWDeviceType, bool]

proc hwDeviceAvailable(t: AVHWDeviceType): bool =
  if t in hwDeviceCache:
    return hwDeviceCache[t]
  var ctx: ptr AVBufferRef = nil
  let ok = av_hwdevice_ctx_create(addr ctx, t, nil, nil, 0) >= 0
  if ctx != nil:
    av_buffer_unref(addr ctx)
  hwDeviceCache[t] = ok
  return ok

proc hwDeviceForEncoder(codec: ptr AVCodec): AVHWDeviceType =
  # Ask the encoder which hw device type it needs.
  var i: cint = 0
  while true:
    let cfg = avcodec_get_hw_config(codec, i)
    if cfg == nil: break
    if cfg.device_type != AV_HWDEVICE_TYPE_NONE:
      return cfg.device_type
    inc i
  return AV_HWDEVICE_TYPE_NONE # software encoder

proc hwEncoderUsable(codec: ptr AVCodec): bool =
  let deviceType = hwDeviceForEncoder(codec)
  # WebCodecs wrappers do not expose an AVHWDeviceContext, but opening them is
  # the operation that calls VideoEncoder/AudioEncoder.isConfigSupported in the
  # browser. Probe those explicitly so `info -encoders` reports runtime support
  # rather than every WebCodecs encoder compiled into the wasm binary.
  let browserEncoder = ($codec.name).endsWith("_web")
  if deviceType == AV_HWDEVICE_TYPE_NONE and not browserEncoder:
    return true
  if deviceType != AV_HWDEVICE_TYPE_NONE and not hwDeviceAvailable(deviceType):
    return false
  if codec.`type` notin [AVMEDIA_TYPE_VIDEO, AVMEDIA_TYPE_AUDIO]:
    return true
  return encoderOpens(codec)

proc printCodecList(ofmt: ptr AVOutputFormat, kind: CodecListKind) =
  var videos, audios, subs, others: seq[string]
  var seen: HashSet[AVCodecID]

  let bestVideo = ofmt.video_codec
  var bestAudio = ofmt.audio_codec
  var bestSubtitle = ofmt.subtitle_codec
  if kind in {clkCodecs, clkEncoders}:
    let fmtName = $ofmt.name
    if fmtName == "mp4" or fmtName == "matroska":
      let d = avcodec_descriptor_get_by_name("opus")
      if d != nil: bestAudio = d.id
    if fmtName == "mp4":
      let d = avcodec_descriptor_get_by_name("mov_text")
      if d != nil: bestSubtitle = d.id

  var opaque: pointer = nil
  while true:
    let codec = av_codec_iterate(addr opaque)
    if codec == nil: break

    # Whether this codec belongs in the listing `kind` asked for.
    let passesKind =
      case kind
      of clkEncoders: av_codec_is_encoder(codec) != 0 and hwEncoderUsable(codec)
      of clkDecoders: av_codec_is_decoder(codec) != 0
      of clkCodecs: codec.id notin seen and avcodec_find_encoder(codec.id) != nil

    if passesKind and
        avformat_query_codec(ofmt, codec.id, FF_COMPLIANCE_EXPERIMENTAL) > 0:
      if kind == clkCodecs:
        seen.incl(codec.id)

      var name = if kind == clkCodecs: $avcodec_get_name(codec.id) else: $codec.name
      if not noColor and
          avformat_query_codec(ofmt, codec.id, FF_COMPLIANCE_STRICT) <= 0:
        name = "\e[31m" & name & "\e[0m"

      template bucket(list, best) =
        if kind in {clkCodecs, clkEncoders} and codec.id == best: list.insert(name, 0)
        else: list.add name

      case codec.`type`
      of AVMEDIA_TYPE_VIDEO: bucket(videos, bestVideo)
      of AVMEDIA_TYPE_AUDIO: bucket(audios, bestAudio)
      of AVMEDIA_TYPE_SUBTITLE: bucket(subs, bestSubtitle)
      else: others.add name

  echo "v: " & videos.join(",")
  echo "a: " & audios.join(",")
  echo "s: " & subs.join(",")
  echo "other: " & others.join(",")

const infoArgumentOptions = {coEncoders, coDecoders, coCodecs}

assertArgumentOptions(infoOptions, infoArgumentOptions)

proc main*(args: seq[string]) =
  av_log_set_level(AV_LOG_QUIET)

  var isJson = false
  var queryExt = ""
  var queryKind: CodecListKind
  var inputFiles: seq[string] = @[]

  parseArgs(args, infoOptions,
      "<file> [options] | -encoders <ext> | -decoders <ext> | -codecs <ext>", "--"):
    case expecting
    of coNone:
      inputFiles.add key
    of coEncoders:
      queryExt = key
      queryKind = clkEncoders
    of coDecoders:
      queryExt = key
      queryKind = clkDecoders
    of coCodecs:
      queryExt = key
      queryKind = clkCodecs
    else:
      discard
    expecting = coNone

  if expecting != coNone:
    error &"-{expecting} requires a format argument"

  if queryExt != "":
    let ofmt = av_guess_format(nil, ("." & queryExt).cstring, nil)
    if ofmt == nil:
      error &"Unknown format: {queryExt}"
    printCodecList(ofmt, queryKind)
    return

  var fileInfo: JsonNode = %* {}
  for inputFile in inputFiles:
    try:
      let formatCtx = av.openFormatCtx(inputFile)
      let mediaInfo = initMediaInfo(formatCtx, inputFile)
      avformat_close_input(addr formatCtx)

      if isJson:
        fileInfo[inputFile] = getJsonInfo(mediaInfo)
      else:
        echo yamlInfo(mediaInfo)
    except IOError:
      if isJson:
        fileInfo[inputFile] = %* {"type": "invalid"}
      else:
        echo inputFile & "\n - Invalid\n"

  if isJson:
    echo pretty(fileInfo)