pkgname=ffmpeg
pkgver=7.1.3
_ver=${pkgver%.*}
pkgdesc='Complete solution to record, convert and stream audio and video'
arch=(x86_64)
homepage=https://ffmpeg.org
license=(GPL-3.0-only)
depends=(
  bzip2
  dav1d
  fontconfig
  freetype
  glibc
  harfbuzz
  libass
  libdrm
  libgl
  libpulse
  libraw1394
  libva
  libwebp
  libxml2
  opus
  x264
  x265
  xz
  zlib
)
makedepends=(
  mesa
  nasm
  vulkan-headers
)
sources=("${pkgname}-${pkgver}.tar.xz"
  "${pkgname}-${_ver}-patchset-2.tar.xz" #from gentoo
)
urls=("https://ffmpeg.org/releases/ffmpeg-${pkgver}.tar.xz"
  "https://dev.gentoo.org/~ionen/distfiles/${sources[1]}"
)
sha512sums=("1231cb6fe8305e040565d9c2a05228af6e90ded88b8548b24b1e7c46964ea25e43db44eb2b677837c0d68bc4e2a10ea5db101c2d2a24d2e3132cd20d599b0da0"
  "bde2e07e2284f9c59bfc3dd448d46f34e14e3983d01baac6b89efac1093dd804318c4770cebe16d84830b34325dcd0aa88cf56136b3529bd36651bb32d73632b"
)

USE="bzip2 dav1d drm fontconfig gpl libass openssl opus postproc pulseaudio truetype vaapi vulkan webp x264 x265 xml zlib"
FFMPEG_IUSE_MAP=(
	# [+]flag[:[^][!]opt1,...][@<v3|nonfree>]], ^ = native-only, ! = override
	# remember to keep LICENSE, REQUIRED_USE, and RESTRICT in sync
	X:libxcb,libxcb-shape,libxcb-shm,libxcb-xfixes,xlib
	alsa
	amf
	amrenc:libvo-amrwbenc@v3
	amr:libopencore-amrnb,libopencore-amrwb@v3
	appkit
	bluray:libbluray
	bs2b:libbs2b
	bzip2:bzlib
	cdio:libcdio
	chromaprint
	codec2:libcodec2
	cuda:cuda-llvm
	+dav1d:libdav1d
	${FFMPEG_UNSLOTTED:+doc:^htmlpages}
	+drm:libdrm
	dvd:libdvdnav,libdvdread
	fdk:libfdk-aac@nonfree
	flite:libflite
	+fontconfig:libfontconfig
	frei0r
	fribidi:libfribidi
	gcrypt
	gme:libgme
	gmp:@v3
	+gnutls # unused if USE=openssl, default for bug #905113,#917627
	+gpl
	gsm:libgsm
	iec61883:libiec61883
	ieee1394:libdc1394
	jack:libjack
	jpeg2k:libopenjpeg
	jpegxl:libjxl
	kvazaar:libkvazaar
	ladspa
	lame:libmp3lame
	lcms:lcms2
	libaom
	libaribb24:@v3 # reminder: req use on gpl unneeded if >=1.0.4 (not in tree)
	+libass
	libcaca
	libilbc
	liblc3
	libplacebo
	librtmp:librtmp
	libsoxr
	lv2
	lzma
	modplug:libmodplug
	nvenc:cuvid,ffnvcodec,nvdec,nvenc
	ocr:libtesseract
	openal
	opencl
	opengl
	openh264:libopenh264
	openmpt:libopenmpt
	openssl:openssl,!gnutls@v3ifgpl # still LGPL2.1+ if USE=-gpl
	opus:libopus
	+postproc # exposed as a USE for clarity with the GPL requirement
	pulseaudio:libpulse
	qrcode:libqrencode
	qsv:libvpl
	quirc:libquirc
	rabbitmq:^librabbitmq # no multilib
	rav1e:^librav1e # no multilib
	rubberband:librubberband
	samba:libsmbclient@v3 # GPL-3+ only
	sdl:sdl2
	shaderc:libshaderc
	snappy:libsnappy
	sndio
	speex:libspeex
	srt:libsrt
	ssh:libssh
	svg:librsvg
	svt-av1:libsvtav1
	theora:libtheora
	+truetype:libfreetype,libharfbuzz
	twolame:libtwolame
	v4l:libv4l2
	vaapi
	vdpau
	vidstab:libvidstab
	vorbis:libvorbis
	vpx:libvpx
	vulkan
	webp:libwebp
	x264:libx264
	x265:libx265
	+xml:libxml2
	xvid:libxvid
	zeromq:^libzmq # no multilib
	zimg:libzimg
	+zlib
	zvbi:libzvbi
)
use() {
  local f=" $1 "
  [[ " ${USE} " == *"${f}"* ]]
}
use_enable() {
  local flag="$1" opt="${2:-$1}"
  if use "${flag}"; then
    printf -- '--enable-%s' "${opt}"
  else
    printf -- '--disable-%s' "${opt}"
  fi
}
multilib_native_use_enable() {
  local flag="$1" opt="${2:-$1}"
  use_enable "${flag}" "${opt}"
}

src_prepare() {
  tar -xf ${distdir}/${sources[0]} --strip-components=1
  tar -xf ${distdir}/${sources[1]}
  for _patch in patches/*; do
    patch -p1 -i ${_patch}
  done
}

ffmpeg_build_optmap() {
  local -n _map_ref="$1"     # nameref: FFMPEG_IUSE_MAP
  local -n _out_ref="$2"     # nameref: 输出数组 conf_opts

  local v flag_raw flag license opt mod
  local -A optmap=() licensemap=()

  for v in "${_map_ref[@]}"; do
    # ebuild: [[ ${v} =~ \+?([^:]+):?([^@]*)@?(.*) ]]
    # 例：
    #   "+drm:libdrm"
    #   "openssl:openssl,!gnutls@v3ifgpl"
    #   "fdk:libfdk-aac@nonfree"
    if [[ ! "${v}" =~ ^\+?([^:]+):?([^@]*)@?(.*)$ ]]; then
      echo "bad map entry: ${v}" >&2
      return 1
    fi

    flag_raw="${BASH_REMATCH[1]}"   # 不含前导 +
    flag="${flag_raw}"
    opt="${BASH_REMATCH[2]}"
    license="${BASH_REMATCH[3]}"

    # 省略 opt 列表则默认等于 flag
    [[ -n "${opt}" ]] || opt="${flag}"

    # 逗号分隔的 opt 列表
    local optlist="${opt//,/ }"
    for opt in ${optlist}; do
      mod="${opt:0:1}"
      # ebuild: v=${v#[\!\^]}
      opt="${opt#!}"
      opt="${opt#^}"

      if [[ "${mod}" == "!" ]]; then
        # override: 若 flag enabled，则强制 disable 该 opt
        if use "${flag}"; then
          optmap["${opt}"]="--disable-${opt}"
          unset 'licensemap["'"${opt}"'"]' || true
        fi
      else
        # 若该 opt 尚未被写入，才生成（避免重复/被前面覆盖）
        if [[ -z "${optmap["${opt}"]+x}" ]]; then
          if [[ "${mod}" == "^" ]]; then
            optmap["${opt}"]="$(multilib_native_use_enable "${flag}" "${opt}")"
          else
            optmap["${opt}"]="$(use_enable "${flag}" "${opt}")"
          fi
          if use "${flag}"; then
            licensemap["${opt}"]="${license}"
          fi
        fi
      fi
    done
  done

  # 处理 license 聚合开关（ebuild：for license in "${licensemap[@]}")
  local lic
  for lic in "${licensemap[@]}"; do
    case "${lic}" in
      v3ifgpl)
        use gpl || continue
        ;&   # fallthrough（bash >=4）
      v3)
        optmap["v3"]="--enable-version3"
        ;;
      nonfree)
        use gpl && optmap["nonfree"]="--enable-nonfree"
        ;;
    esac
  done

  # 输出：把 optmap 的值都塞进 _out_ref（顺序不保证；需要稳定顺序可再排序）
  local k
  for k in "${!optmap[@]}"; do
    _out_ref+=( "${optmap[$k]}" )
  done
}

src_build() {
  sed -i '/cflags -fdiagnostics-color/d' configure

  local prefix="/usr"
  local conf_args=(
    --prefix="${prefix}"
    --libdir="${prefix}"/lib
    --shlibdir="${prefix}"/lib
    --mandir="${prefix}"/share/man
    --docdir=/usr/share/doc/${pkgname}-${pkgver}/html

    --disable-stripping
    --disable-debug
    --disable-optimizations
    --optflags=' '

    # basic defaults that should not really need a USE
    --enable-iconv
    --enable-pic
    --enable-shared
    --disable-static
    --enable-manpages
    --disable-podpages
    --disable-txtpages
    # disabled primarily due to being unpackaged
    --disable-decklink
    --disable-libaribcaption
    --disable-libdavs2
    --disable-libklvanc
    --disable-liblcevc-dec
    --disable-libmysofa
    --disable-libopenvino
    --disable-libshine
    --disable-libtls
    --disable-libuavs3d
    --disable-libvvenc
    --disable-libxavs
    --disable-libxavs2
    --disable-libxevd
    --disable-libxeve
    --disable-pocketsphinx
    --disable-rkmpp
    --disable-vapoursynth

    # disabled for other or additional reasons
    --disable-cuda-nvcc # prefer cuda-llvm for less issues
    --disable-libcelt # obsolete (bug #664158)
    --disable-libglslang # prefer USE=shaderc (bug #918989,#920283,#922333)
    --disable-liblensfun # https://trac.ffmpeg.org/ticket/9112 (abandoned?)
    --disable-libmfx # prefer libvpl for USE=qsv
    --disable-libnpp # deprecated and not supported for cuda 13.0+
    --disable-libopencv # leaving for later due to circular opencv[ffmpeg]
    --disable-librist # librist itself needs attention first (bug #822012)
    --disable-libtensorflow # causes headaches, and is gone
    --disable-libtorch # support may need special attention (bug #936127)
    --disable-libvmaf # use ffmpeg-8+ instead, needs old vmaf (bug#968554)
    --disable-mbedtls # messy with slots, tests underlinking issues
    --disable-mmal # prefer USE=soc
    --disable-omx # unsupported (bug #653386)
    --disable-omx-rpi # ^
  )

  ffmpeg_build_optmap FFMPEG_IUSE_MAP conf_args
  leaf_info "${conf_args[*]}"

  ./configure "${conf_args[@]}"
  make V=1
}

src_check() {
  local -x LD_LIBRARY_PATH=$(printf %s: "${srcdir}"/lib*)${LD_LIBRARY_PATH}
  make V=1 -k fate
}

src_install() {
  make DESTDIR="${pkgdir}" install
}

# vim:ft=sh syn=sh et sw=2:
