#!/usr/bin/env bash
#
# build_ffmpeg_program.sh - build static ffmpeg + ffprobe from FFmpeg's own
# release source, for Linux (native) or Windows (cross-compiled with
# MinGW-w64, on this same Linux runner), in a GPL or LGPL variant.
#
# Why: docs/proposals/FFMPEG_OWN_BUILD.md (#803, GPLv3 Sec1 gap with
# gyan.dev). Linux ships no ffmpeg/ffprobe program at all today; Windows
# bundles gyan.dev's static build, whose ~35-library recipe we do not hold
# source for. This script builds both ourselves, from a pinned, verified
# source tree per dependency, so docs/proposals/FFMPEG_OWN_BUILD.md's
# Corresponding Source section has something real to publish.
#
# This is the PROGRAM build (ffmpeg/ffprobe CLIs that FfmpegService shells
# out to) - NOT the in-app player build (libmpv + its own FFmpeg, shared
# libraries loaded into the process, scripts/release/build_lgpl_player_linux.sh,
# #798). Different script, different consumer, different output shape.
#
# Usage:
#   bash scripts/release/build_ffmpeg_program.sh <linux-x64|win-x64> <gpl|lgpl> <outdir>
#
# Output, under OUTDIR:
#   ffmpeg / ffmpeg.exe, ffprobe / ffprobe.exe   - static executables
#   BUILDINFO.txt                                - versions, configure line,
#                                                   `ffmpeg -buildconf`, every
#                                                   component's sha256
#   source/                                      - the Corresponding Source:
#                                                   every pinned tarball as
#                                                   downloaded, this script,
#                                                   and BUILDINFO.txt
#
# Regardless of OUTDIR, every run also (re)writes
# scripts/release/ffmpeg_components.json at a fixed repo-relative path - see
# write_components_json() below. It is deliberately not schema-versioned
# (CLAUDE.md Sec4's "NO schema field" is explicit in the task brief): another
# worker's THIRD_PARTY_NOTICES generator reads it, and the two must describe
# the same thing without implying the exportable-artifact versioning contract
# that field names elsewhere in this repo.
#
# Environment:
#   GMS_FFMPEG_CACHE     where finished dependency builds are kept (default
#                        ~/.cache/gms-ffmpeg-program). The self-hosted runner
#                        keeps this between runs - an empty cache builds
#                        everything from scratch (first run: much longer).
#   GMS_FFMPEG_JOBS      parallel compile jobs (default: nproc)
#   GMS_FFMPEG_SKIP_APT  1 = do not apt-get install build dependencies
#
# Licence rules this script enforces (see want_define() calls below, same
# pattern as build_lgpl_player_linux.sh's config.h assertions - a silently
# dropped feature is worse than a loud build failure):
#   * lgpl variant: no --enable-gpl, no libx264, no libx265, no other
#     GPL-only component. Never --enable-nonfree in EITHER variant - nothing
#     built here is non-free, so the result is always a clean GPL or LGPL
#     binary, never "+ nonfree".
#   * Every component this binary claims to support (see the inventory in
#     docs/proposals/FFMPEG_OWN_BUILD.md) is verified present in FFmpeg's
#     own generated config.h after configure - a missing nasm or a cross
#     pkg-config miss fails the build instead of shipping a crippled ffmpeg.
#
# Pins: every tarball below was downloaded (or, for SVT-AV1 and x264, built
# locally with `git archive` from a pinned commit - see fetch_git_archive())
# and sha256-computed from the actual bytes while writing this script, never
# copied from a vendor page or a CI log. A GitLab `/-/archive/` or gitiles
# `+archive` URL is NEVER an acceptable pin source here - both regenerate
# their tarball per request and the bytes (hence the sha256) can change
# later without warning; dav1d, libaom, SVT-AV1 and x264 all originally
# pointed at one before this was understood (run 36799732356 failed on
# dav1d's copy of the bug in its first seconds). FFmpeg's own tarball and
# libaom's are additionally GPG-verified: FFmpeg against the release key
# fingerprint already trusted elsewhere in this repo
# (build_lgpl_player_linux.sh, .github/workflows/corresponding-source.yml),
# libaom against AOMedia's own release-signing key (aom_verify_signature()) -
# libaom's release bucket has no .sha256 sidecar, only a detached signature.
# Bump a version and its sha256 TOGETHER.

set -euo pipefail

# ---------------------------------------------------------------------------
# Pins
# ---------------------------------------------------------------------------

FFMPEG_VERSION="9.0.2"
FFMPEG_URL="https://ffmpeg.org/releases/ffmpeg-${FFMPEG_VERSION}.tar.xz"
FFMPEG_SHA256="8c3850283eb25fa026482078a04051e0be17347b09ef81a0849bec15a96e002e"
# Same key as build_lgpl_player_linux.sh / corresponding-source.yml.
FFMPEG_KEY_FPR="FCF986EA15E6E293A5644F10B4322F04D67658D8"

# x264 offers no stable release tarball - only GitLab's generated
# `/-/archive/` endpoint, which is NOT byte-stable (GitLab regenerates it on
# demand; see the dav1d lesson below - this pin used to point there and
# would eventually break the same way). Fetched via `git fetch --depth 1
# origin <commit>` instead (code.videolan.org allows fetch-by-exact-SHA),
# then archived locally with `git archive` - see fetch_git_archive().
# X264_REF is a commit on VideoLAN's "stable" branch, not a tag.
X264_REPO="https://code.videolan.org/videolan/x264.git"
X264_REF="b35605ace3ddf7c1a5d67a2eb553f034aef41d55" # VideoLAN "stable" branch head
X264_SHA256="54788da66c57f53a046e16747807668d05da24f1cfd0372299b5311b1367695b" # git-archive output, not a download

X265_VERSION="4.2"
X265_URL="https://bitbucket.org/multicoreware/x265_git/get/${X265_VERSION}.tar.gz"
X265_SHA256="0a3d41f6b4e2fe5a49d783d6631bd1a49c44cdf999074a3ff09e2cb71ac8ed33"

# SVT-AV1 has no stable release tarball either - same GitLab generated-archive
# non-determinism as x264 above. Fetched by tag via `git fetch --depth 1
# origin <tag>`, with the resolved commit asserted against SVTAV1_COMMIT
# before anything is archived (fails loudly if upstream ever moves the tag).
SVTAV1_TAG="v4.2.0"
SVTAV1_REPO="https://gitlab.com/AOMediaCodec/SVT-AV1.git"
SVTAV1_COMMIT="9292ec8e32bce26f781f277ec8739b53426c4300"
SVTAV1_SHA256="753bcc1ba62ca425ad003b22c92609dce9ecbbec2cd572ecf298df9d136d69bc" # git-archive output, not a download

# libaom: the googlesource `+archive` tarball this used to pin is also
# generated-on-demand and non-deterministic (same family of bug as the
# gitlab archives above - caught only because dav1d's copy of the same
# problem broke the first real build, run 36799732356). AOMedia's own
# release bucket publishes a real, static tarball instead; it ships no
# .sha256 sidecar, so this build verifies the detached GPG signature
# alongside it (AOMedia's own release-signing key) rather than trusting the
# bucket's bytes on their own - see the aom_verify_signature call in
# fetch_all_sources().
AOM_VERSION="3.15.1"
AOM_URL="https://storage.googleapis.com/aom-releases/libaom-${AOM_VERSION}.tar.gz"
AOM_SHA256="8ca0c52746174603500f0adb6f2a215d69c9ca2aab2acb3caa06fb791d8d01bf"
AOM_KEY_FPR="B002F08B74A148DAA01F7123A48E86DB0B830498" # "AOMedia release signing key <av1-discuss@aomedia.org>"

VPX_VERSION="v1.17.0"
VPX_URL="https://github.com/webmproject/libvpx/archive/refs/tags/${VPX_VERSION}.tar.gz"
VPX_SHA256="1020f184046187baa2985dbde38e0691f49c44088bca7a1842b0236c6081dc0a"

OPUS_VERSION="1.5.2"
OPUS_URL="https://downloads.xiph.org/releases/opus/opus-${OPUS_VERSION}.tar.gz"
OPUS_SHA256="65c1d2f78b9f2fb20082c38cbe47c951ad5839345876e46941612ee87f9a7ce1"

# The GitLab `/-/archive/` tarball this used to pin is generated on demand
# and NOT byte-stable - GitLab re-packs it per request, so the bytes (and
# therefore the sha256) can and did change (run 36799732356 failed in its
# first seconds on this exact mismatch). VideoLAN's own download server
# publishes a static release tarball with a `.sha256` sidecar instead - use
# that.
DAV1D_VERSION="1.5.4"
DAV1D_URL="https://downloads.videolan.org/pub/videolan/dav1d/${DAV1D_VERSION}/dav1d-${DAV1D_VERSION}.tar.xz"
DAV1D_SHA256="686616b7c69eb88d44459391ab25cac13b6647a3b288835c5784e71c1514a5c5" # matches the published .sha256

ZIMG_VERSION="release-3.0.6"
ZIMG_URL="https://github.com/sekrit-twc/zimg/archive/refs/tags/${ZIMG_VERSION}.tar.gz"
ZIMG_SHA256="be89390f13a5c9b2388ce0f44a5e89364a20c1c57ce46d382b1fcc3967057577"

WEBP_VERSION="v1.6.0"
WEBP_URL="https://github.com/webmproject/libwebp/archive/refs/tags/${WEBP_VERSION}.tar.gz"
WEBP_SHA256="93a852c2b3efafee3723efd4636de855b46f9fe1efddd607e1f42f60fc8f2136"

LIBASS_VERSION="0.17.5"
LIBASS_URL="https://github.com/libass/libass/releases/download/${LIBASS_VERSION}/libass-${LIBASS_VERSION}.tar.gz"
LIBASS_SHA256="caab4b993dd7be6187c55623b789ed75dddefea6e65938af134637c732fe094a"

FREETYPE_VERSION="2.14.3"
FREETYPE_URL="https://download.savannah.gnu.org/releases/freetype/freetype-${FREETYPE_VERSION}.tar.xz"
FREETYPE_SHA256="36bc4f1cc413335368ee656c42afca65c5a3987e8768cc28cf11ba775e785a5f"

FRIBIDI_VERSION="1.0.17"
FRIBIDI_URL="https://github.com/fribidi/fribidi/releases/download/v${FRIBIDI_VERSION}/fribidi-${FRIBIDI_VERSION}.tar.xz"
FRIBIDI_SHA256="6949dcde27d41cebad1fd741fcafc36d55a1020d2d872d4a6eb3914caabbada2"

HARFBUZZ_VERSION="14.5.1"
HARFBUZZ_URL="https://github.com/harfbuzz/harfbuzz/releases/download/${HARFBUZZ_VERSION}/harfbuzz-${HARFBUZZ_VERSION}.tar.xz"
# Round 2 (run 36816127171) caught this pin was simply wrong - re-downloaded
# and sha256-computed fresh; the new value also matches what the CI runner
# independently computed from its own download, on a different machine.
HARFBUZZ_SHA256="7e2fa4e8c7c98e8d8140671f5772542afaaa6acccfbd746506886b6d85f7f8d6"

# libunibreak: libass's line-breaking library (zlib licence). libass only
# needs set_linebreaks_utf32 (ass_render.c), which 8.0 keeps; 8.0 dropped the
# incremental API libass never used. Release tarball from the maintainer's
# repository (adah1972), sha256 computed from a fresh download 2026-10-05.
# Why it is built here at all: see build_libunibreak().
UNIBREAK_VERSION="8.0"
UNIBREAK_TAG="libunibreak_8_0"
UNIBREAK_URL="https://github.com/adah1972/libunibreak/releases/download/${UNIBREAK_TAG}/libunibreak-${UNIBREAK_VERSION}.tar.gz"
UNIBREAK_SHA256="9c4fad6e517338a098373acc9f35579ae2c325e6446666fb9ac2666ba15ceba4"

# expat: fontconfig's XML parser for fonts.conf/conf.d (Linux only - see
# FONTCONFIG_VERSION below). Standard GitHub-release tarball; asset name
# does not match the git tag (R_2_8_5 tag, expat-2.8.5.tar.xz asset).
EXPAT_VERSION="2.8.5"
EXPAT_TAG="R_2_8_5"
EXPAT_URL="https://github.com/libexpat/libexpat/releases/download/${EXPAT_TAG}/expat-${EXPAT_VERSION}.tar.xz"
EXPAT_SHA256="1e727b8933ec51a77a9a9d9afcf8e688bce45d907c13e36ab7393fe36e703182"

# fontconfig: libass's Linux system font provider - libass's configure.ac
# requires fontconfig (Linux), CoreText (Apple) or DirectWrite (Windows);
# without one it aborts with "No system font provider!" (run 36816406247).
# Built --sysconfdir=/etc --localstatedir=/var so the compiled-in default
# paths are the END USER's /etc/fonts (already populated by their distro's
# own fontconfig package) and /var/cache/fontconfig, never this build
# host's - see build_fontconfig()'s DESTDIR handling. Windows needs no
# library here at all; see build_libass() for DirectWrite instead.
FONTCONFIG_VERSION="2.16.0"
FONTCONFIG_URL="https://www.freedesktop.org/software/fontconfig/release/fontconfig-${FONTCONFIG_VERSION}.tar.xz"
FONTCONFIG_SHA256="6a33dc555cc9ba8b10caf7695878ef134eeb36d0af366041f639b1da9b6ed220"

NVHEADERS_VERSION="n13.1.15.0"
NVHEADERS_URL="https://github.com/FFmpeg/nv-codec-headers/archive/refs/tags/${NVHEADERS_VERSION}.tar.gz"
NVHEADERS_SHA256="2255bc74d038b95aa4be30f5f66322c2176acbdb90ada1851db6993536fbeaf7"

LIBVPL_VERSION="v2.17.0"
LIBVPL_URL="https://github.com/intel/libvpl/archive/refs/tags/${LIBVPL_VERSION}.tar.gz"
LIBVPL_SHA256="4de3e2faf1e8307fb282e4a43f443191810f6a6b0a484fffa7995ba1c814c6ec"

AMF_VERSION="v1.5.3"
AMF_URL="https://github.com/GPUOpen-LibrariesAndSDKs/AMF/releases/download/${AMF_VERSION}/AMF-headers-${AMF_VERSION}.tar.gz"
AMF_SHA256="570c8f6593b8c24a6e47a0a9c59b216a7198138e660ba4011590ae913343d5c3"

# The headers-only release asset above ships no LICENSE file of its own
# (checked by hand: AMF-headers-v1.5.3.tar.gz has no COPYING/LICENSE/NOTICE
# member at any depth, 61 entries total, all headers). AMD's MIT text for
# this project lives in the main AMF repo's LICENSE.txt at the same tag
# instead - fetched and sha256-verified the same as every other download in
# this script, not copy-pasted.
AMF_LICENSE_URL="https://raw.githubusercontent.com/GPUOpen-LibrariesAndSDKs/AMF/${AMF_VERSION}/LICENSE.txt"
AMF_LICENSE_SHA256="eb297397aaa455b5668ab67d216b83828466152dab123fa92384c6ec16b74170"

LIBVA_VERSION="2.24.1"
LIBVA_URL="https://github.com/intel/libva/releases/download/${LIBVA_VERSION}/libva-${LIBVA_VERSION}.tar.bz2"
LIBVA_SHA256="eec6050b52876f229bd35e9df17cd31a06785e18e6f7990c445b584628483d67"

# zlib: FFmpeg's native png/apng encoder+decoder (image2 format, used by
# lib/services/photo/photo_convert_service.dart) links zlib for DEFLATE.
# Not bzip2/lzma - no demuxer that needs either appears anywhere in lib/
# (grepped), so this build does not carry them (--enable-bzlib/--enable-lzma
# dropped from the configure line docs/proposals/FFMPEG_OWN_BUILD.md
# originally listed; that doc is corrected in the same commit as this one).
ZLIB_VERSION="1.3.2"
ZLIB_URL="https://github.com/madler/zlib/releases/download/v${ZLIB_VERSION}/zlib-${ZLIB_VERSION}.tar.gz"
ZLIB_SHA256="bb329a0a2cd0274d05519d61c667c062e06990d72e125ee2dfa8de64f0119d16"

# Kvazaar (HEVC) and OpenH264 (H.264): the processor fallback encoders for
# when no graphics-card encoder is available (owner decision 2026-10-02,
# #816). Both BSD-licensed (LICENSE read and confirmed while pinning this:
# Kvazaar 3-clause, OpenH264 2-clause - neither the GPL x264/x265 pair
# above), so both are built in EVERY variant, not gated by $VARIANT.
#
# Kvazaar ships a real, static release tarball asset (unlike x264/SVT-AV1
# above) - use it directly, no git-archive workaround needed.
KVAZAAR_VERSION="2.3.2"
KVAZAAR_URL="https://github.com/ultravideo/kvazaar/releases/download/v${KVAZAAR_VERSION}/kvazaar-${KVAZAAR_VERSION}.tar.gz"
KVAZAAR_SHA256="b95d2e20f2b0d8d7ed320055740be2e7a730abe28b153b5a788cfca371cc38b2"

# OpenH264 publishes no source tarball at all on its GitHub Releases (the
# v2.6.0 release has zero assets - checked while pinning this) - same
# git-archive treatment as x264/SVT-AV1 above, with the same caveat: a git
# version upgrade on the runner can change the archive's bytes (hence its
# sha256) - re-pin from the build's own error message if that happens.
OPENH264_TAG="v2.6.0"
OPENH264_REPO="https://github.com/cisco/openh264.git"
OPENH264_COMMIT="652bdb7719f30b52b08e506645a7322ff1b2cc6f"
OPENH264_SHA256="351414149c245f8d0aa38bb69a51c4aa5bad722ea95339ee1a3dcbd53d67904c" # git-archive output, not a download

# Component names shared by both licence variants (the gpl variant adds
# x264+x265 on top of this list; ffmpeg itself isn't in it either - see
# VARIANT/write_components_json() below). Single source of truth for
# write_components_json() (the "components" file) AND collect_licenses()
# (each component's licence-folder name), so the two can never name a
# component differently - several of these are target-conditional (expat/
# fontconfig/libva: Linux only: amf-headers: Windows only), which is why
# collect_licenses() filters this list per-target rather than using it as-is.
COMMON_COMPONENT_NAMES=(
  svt-av1 kvazaar libaom libvpx openh264 libopus dav1d zimg libwebp libass
  freetype fribidi harfbuzz libunibreak expat fontconfig nv-codec-headers libvpl
  amf-headers libva zlib
)

# ---------------------------------------------------------------------------
# Small helpers
# ---------------------------------------------------------------------------

say() { printf 'build_ffmpeg_program: %s\n' "$*" >&2; }
die() { printf 'build_ffmpeg_program: ERROR: %s\n' "$*" >&2; exit 1; }

usage() {
  echo "usage: $0 <linux-x64|win-x64> <gpl|lgpl> <outdir>" >&2
  exit 2
}

[ $# -eq 3 ] || usage
TARGET="$1"
VARIANT="$2"
OUTDIR="$3"

case "$TARGET" in
  linux-x64|win-x64) ;;
  *) die "unknown target '$TARGET' (want linux-x64 or win-x64)" ;;
esac
case "$VARIANT" in
  gpl|lgpl) ;;
  *) die "unknown variant '$VARIANT' (want gpl or lgpl)" ;;
esac

SCRIPT_PATH="$(readlink -f "${BASH_SOURCE[0]}")"
SCRIPT_DIR="$(dirname "$SCRIPT_PATH")"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
JOBS="${GMS_FFMPEG_JOBS:-$(nproc)}"

if [ "$TARGET" = "win-x64" ]; then
  MINGW=1
  HOST_TRIPLE="x86_64-w64-mingw32"
  CROSS="${HOST_TRIPLE}-"
  EXE_SUFFIX=".exe"
else
  MINGW=0
  HOST_TRIPLE=""
  CROSS=""
  EXE_SUFFIX=""
fi

# ---------------------------------------------------------------------------
# Build dependencies on the runner (same sudo -n convention as
# build_lgpl_player_linux.sh - passwordless sudo covers apt-get only).
# ---------------------------------------------------------------------------

APT_DEPS_COMMON=(
  build-essential pkg-config nasm cmake meson ninja-build
  python3 gnupg curl ca-certificates xz-utils patchelf
  autoconf automake libtool git
)
APT_DEPS_LINUX=(libva-dev libdrm-dev gperf)
APT_DEPS_WIN=(
  mingw-w64 gcc-mingw-w64-x86-64 g++-mingw-w64-x86-64
  binutils-mingw-w64-x86-64
)

install_deps() {
  [ "${GMS_FFMPEG_SKIP_APT:-0}" = "1" ] && return 0
  local want=("${APT_DEPS_COMMON[@]}")
  if [ "$MINGW" = "1" ]; then
    want+=("${APT_DEPS_WIN[@]}")
  else
    want+=("${APT_DEPS_LINUX[@]}")
  fi
  local missing=() p
  for p in "${want[@]}"; do
    dpkg-query -W -f='${Status}' "$p" 2>/dev/null | grep -q 'install ok installed' \
      || missing+=("$p")
  done
  [ "${#missing[@]}" -eq 0 ] && return 0
  say "installing build dependencies: ${missing[*]}"
  local apt=(apt-get)
  [ "$(id -u)" -eq 0 ] || apt=(sudo -n apt-get)
  export DEBIAN_FRONTEND=noninteractive
  "${apt[@]}" install -y --no-install-recommends "${missing[@]}" \
    || { "${apt[@]}" update && "${apt[@]}" install -y --no-install-recommends "${missing[@]}"; } \
    || die "could not install: ${missing[*]}"
  if [ "$MINGW" = "1" ]; then
    # Select the POSIX threading model: needed for std::thread/pthread
    # emulation under mingw (winpthreads), which several dependencies
    # (meson-based ones especially) assume is available. The win32 model
    # is the other alternative and lacks it. Best-effort: this runner's
    # passwordless sudo covers apt-get only (same constraint
    # build_lgpl_player_linux.sh's install_deps documents), so a non-root,
    # non-apt sudo call here is expected to no-op - current Ubuntu already
    # defaults x86_64-w64-mingw32-gcc to -posix, which is why this is a
    # belt-and-braces check rather than the only thing selecting it.
    local uamode=(update-alternatives)
    [ "$(id -u)" -eq 0 ] || uamode=(sudo -n update-alternatives)
    for alt in x86_64-w64-mingw32-gcc x86_64-w64-mingw32-g++; do
      local choice
      choice="$(update-alternatives --list "$alt" 2>/dev/null | grep -- '-posix$' | head -n1 || true)"
      if [ -n "$choice" ]; then
        "${uamode[@]}" --set "$alt" "$choice" 2>/dev/null \
          || say "could not select $choice for $alt (non-fatal - continuing with whatever is already the default)"
      fi
    done
  fi
}

# ---------------------------------------------------------------------------
# Fetch + extract
# ---------------------------------------------------------------------------

# Second sources for upstream hosts that go down. download.savannah.gnu.org
# refused every connection for the whole r4 run on 2026-10-05, which failed a
# cold build on FreeType. The sha256 pin decides either way, so a mirror can
# only ever supply the same bytes; it is tried only when the primary cannot
# be downloaded at all, never after a hash mismatch.
mirrors_for() { # url
  case "$1" in
    https://download.savannah.gnu.org/releases/freetype/*)
      printf '%s\n' "https://downloads.sourceforge.net/project/freetype/freetype2/${FREETYPE_VERSION}/$(basename "$1")" ;;
  esac
}

fetch_pinned() { # url sha256 dest
  local actual url
  # fetch_all_sources() already pulled every tarball this (target,variant)
  # needs before build_all() runs, so every *_build() function's own
  # fetch_pinned call would otherwise re-download a file already on disk -
  # skip it when the bytes already there match the pin.
  if [ -f "$3" ]; then
    actual="$(sha256sum "$3" | cut -d' ' -f1)"
    [ "$actual" = "$2" ] && return 0
  fi
  local -a urls=("$1")
  while IFS= read -r url; do
    [ -n "$url" ] && urls+=("$url")
  done < <(mirrors_for "$1")
  for url in "${urls[@]}"; do
    if curl -fsSL --retry 5 --retry-delay 5 --retry-all-errors -o "$3" "$url"; then
      actual="$(sha256sum "$3" | cut -d' ' -f1)"
      [ "$actual" = "$2" ] || die "sha256 mismatch for $(basename "$3") from $url: expected $2, got $actual - refusing to build"
      [ "$url" = "$1" ] || say "fetched $(basename "$3") from the mirror $url (primary unreachable); sha256 matches the pin"
      return 0
    fi
    say "download failed: $url"
  done
  die "download failed: $1 (and every mirror)"
}

# fetch_git_archive name repo ref commit sha256 dest prefix
#   For dependencies with no stable release tarball - only a host (GitLab)
#   that generates `/-/archive/` tarballs on demand, which are NOT
#   byte-stable (see the dav1d/SVT-AV1/x264 comments above this file's pin
#   block). Clones the exact pinned commit instead of trusting a generated
#   archive's bytes, then builds OUR OWN tarball with `git archive` - which
#   IS byte-reproducible for a given commit + git version (verified by hand
#   while writing this: two `git archive` runs of the same commit, seconds
#   apart, produced identical sha256 output; the gzip wrapper embeds no
#   timestamp because git pipes it through stdin, not a named file).
#   ref: a tag/branch name to fetch (`git fetch --depth 1 origin "$ref"`).
#     Empty string: fetch "$commit" directly instead (code.videolan.org -
#     and apparently every modern git host tested here - allows fetching an
#     exact commit SHA directly; used for x264, which is pinned to a
#     "stable"-branch commit rather than a tag).
#   Either way, the checked-out HEAD is asserted to equal "$commit" before
#   anything is archived - a moved tag or a force-pushed branch fails the
#   build loudly instead of silently building different source than the one
#   that was reviewed.
fetch_git_archive() {
  local name="$1" repo="$2" ref="$3" commit="$4" sha256="$5" dest="$6" prefix="$7"
  local actual
  if [ -f "$dest" ]; then
    actual="$(sha256sum "$dest" | cut -d' ' -f1)"
    [ "$actual" = "$sha256" ] && return 0
  fi
  local tmp="$WORK/gitsrc/$name"
  rm -rf "$tmp"
  mkdir -p "$tmp"
  git -C "$tmp" init -q
  # Force this OFF regardless of the invoking machine's global gitconfig -
  # `git archive` applies the `text`/eol conversion the same way a checkout
  # does, so a clone made with core.autocrlf=true produces different bytes
  # (hence a different sha256) than one made with it false, for the exact
  # same commit. This is not hypothetical: the first pin for this (computed
  # on a Windows box with Git for Windows' autocrlf=true default) mismatched
  # the Linux runner's archive by this exact mechanism - confirmed by
  # reproducing the runner's hash locally after setting this.
  git -C "$tmp" config core.autocrlf false
  git -C "$tmp" remote add origin "$repo"
  if [ -n "$ref" ]; then
    logged "$name-fetch" git -C "$tmp" fetch --depth 1 origin "$ref"
  else
    logged "$name-fetch" git -C "$tmp" fetch --depth 1 origin "$commit"
  fi
  git -C "$tmp" checkout -q FETCH_HEAD
  local got
  got="$(git -C "$tmp" rev-parse HEAD)"
  [ "$got" = "$commit" ] \
    || die "$name: resolved commit $got does not match pinned $commit - upstream ref moved, update the pin after reviewing what changed"
  git -C "$tmp" archive --format=tar.gz --prefix="$prefix/" HEAD -o "$dest" \
    || die "$name: git archive failed"
  actual="$(sha256sum "$dest" | cut -d' ' -f1)"
  [ "$actual" = "$sha256" ] \
    || die "$name: git-archive sha256 mismatch: expected $sha256, got $actual (a git version upgrade can change archive output - re-pin if that's what happened, after confirming nothing else changed)"
}

# aom_verify_signature tarball
#   libaom's release bucket ships no .sha256 sidecar (confirmed: a direct
#   request 404s) - only a detached GPG signature (<tarball>.asc). The pinned
#   AOM_SHA256 above is still the primary gate (computed from bytes
#   downloaded while writing this script); this is the same belt-and-braces
#   authenticity check build_ffmpeg() already does for FFmpeg's own tarball,
#   against AOMedia's release-signing key instead of FFmpeg's. Same pattern:
#   fetch the key over plain HTTPS (no keyserver protocol / dirmngr
#   dependency), isolate it in its own GNUPGHOME, assert the fingerprint
#   before trusting anything it signs.
aom_verify_signature() {
  local tarball="$1" asc="$1.asc"
  curl -fsSL --retry 5 --retry-delay 5 -o "$asc" "$AOM_URL.asc" \
    || die "download failed: $AOM_URL.asc"
  (
    GNUPGHOME="$WORK/gnupg-aom"
    export GNUPGHOME
    mkdir -p "$GNUPGHOME" && chmod 700 "$GNUPGHOME"
    curl -fsSL --retry 5 --retry-delay 5 \
      -o "$WORK/aom-release-key.asc" \
      "https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x${AOM_KEY_FPR}&options=mr" \
      || die "could not fetch AOMedia release key $AOM_KEY_FPR"
    gpg --batch --quiet --import "$WORK/aom-release-key.asc" 2>/dev/null
    fpr="$(gpg --batch --with-colons --fingerprint | awk -F: '$1=="fpr"{print $10; exit}')"
    [ "$fpr" = "$AOM_KEY_FPR" ] || die "keyserver served key $fpr, expected $AOM_KEY_FPR"
    gpg --batch --quiet --verify "$asc" "$tarball" 2>/dev/null \
      || die "libaom $AOM_VERSION signature does not verify"
  )
}

# extract_src tarball destdir strip
#   strip=1 (default): the tarball has one wrapping top-level directory
#     (every GitHub/GitLab/Bitbucket archive here) - stripped on extraction.
#   strip=0: the tarball's files sit at the archive root (libaom's
#     googlesource +archive tarball is the one case of this).
extract_src() {
  local tarball="$1" destdir="$2" strip="${3:-1}"
  mkdir -p "$destdir"
  if [ "$strip" = "1" ]; then
    tar xf "$tarball" -C "$destdir" --strip-components=1
  else
    tar xf "$tarball" -C "$destdir"
  fi
}

# Assert a #define in a generated config.h: file NAME expected-value. Same
# pattern as build_lgpl_player_linux.sh - a feature that silently didn't
# compile in is worse than a build that refuses to finish.
want_define() {
  local got
  got="$(awk -v n="$2" '$1 == "#define" && $2 == n {print $3; exit}' "$1")"
  [ "$got" = "$3" ] || die "$1: $2 is '${got:-unset}', expected $3"
}

# Run a build step with output in a log; show the tail on failure.
logged() { # name cmd...
  local name="$1"; shift
  "$@" > "$WORK/log-$name.log" 2>&1 || { tail -n 80 "$WORK/log-$name.log" >&2; die "$name failed"; }
}

# FFmpeg's configure prints only "X not found"; the reason (a missing symbol,
# a library left off the link line) is in ffbuild/config.log. Relies on the
# caller's `src` (bash locals are visible to called functions).
ffmpeg_configure() { # cmd...
  "$@" > "$WORK/log-ffmpeg-configure.log" 2>&1 || {
    tail -n 40 "$WORK/log-ffmpeg-configure.log" >&2
    # The failing check is named in "ERROR: <name> requested but not found"
    # or "ERROR: <pkg> ... not found"; print config.log from that check on.
    local missing ln
    missing="$(sed -n 's/^ERROR: \([A-Za-z0-9_]*\) .*not found.*/\1/p' \
      "$WORK/log-ffmpeg-configure.log" | head -n 1)"
    # `|| true` on the whole pipeline: under set -eo pipefail, a bare
    # `ln=$(...)` assignment whose command substitution exits non-zero
    # (grep finding no match, which is the EXPECTED case whenever
    # config.log has no check_/require_ line for $missing) kills the
    # script right here, silently - no diagnostic, no die() message,
    # nothing past this line. That's exactly what happened chasing the
    # kvazaar win-x64 failure (#816): the log just stopped after FFmpeg's
    # own one-line error, because config.log never logs a require_pkg_config
    # line starting with "check_"/"require" for every macro name. Diagnosed
    # once, fixed for every future missing-dependency case this falls
    # through to.
    ln="$(grep -n "^check_[a-z_]* $missing \|^require[a-z_]* $missing " \
      "$src/ffbuild/config.log" 2>/dev/null | tail -n 1 | cut -d: -f1 || true)"
    if [ -n "$ln" ]; then
      echo "---- ffbuild/config.log from the $missing check (line $ln) ----" >&2
      tail -n "+$ln" "$src/ffbuild/config.log" | head -n 60 >&2
    else
      echo "---- ffbuild/config.log (tail) ----" >&2
      tail -n 150 "$src/ffbuild/config.log" >&2 || true
    fi
    case "$missing" in
      vaapi)
        echo "---- pkg-config view of libva ----" >&2
        pkg-config --modversion libva >&2 || true
        pkg-config --cflags --libs --static libva >&2 || true
        ls -l "$PREFIX"/lib/libva* "$PREFIX"/lib/pkgconfig/libva* >&2 || true
        ;;
      kvazaar|libkvazaar)
        echo "---- pkg-config view of kvazaar ----" >&2
        pkg-config --modversion kvazaar >&2 || true
        pkg-config --cflags --libs --static kvazaar >&2 || true
        ls -l "$PREFIX"/lib/libkvazaar* "$PREFIX"/lib/pkgconfig/kvazaar* >&2 || true
        cat "$PREFIX/lib/pkgconfig/kvazaar.pc" >&2 2>/dev/null || true
        ;;
      openh264|libopenh264)
        echo "---- pkg-config view of openh264 ----" >&2
        pkg-config --modversion openh264 >&2 || true
        pkg-config --cflags --libs --static openh264 >&2 || true
        ls -l "$PREFIX"/lib/libopenh264* "$PREFIX"/lib/pkgconfig/openh264* >&2 || true
        cat "$PREFIX/lib/pkgconfig/openh264.pc" >&2 2>/dev/null || true
        ;;
    esac
    die "ffmpeg-configure failed"
  }
}

# ---------------------------------------------------------------------------
# Cache: the whole dependency+ffmpeg install PREFIX, keyed by this script's
# own sha256 (any pin/flag edit invalidates it) plus target+variant, so the
# 4 (target,variant) combinations each get their own slot. Mirrors
# build_lgpl_player_linux.sh's cache, which already proved the pattern on
# this runner.
# ---------------------------------------------------------------------------

RECIPE_ID="$(sha256sum "$SCRIPT_PATH" | cut -c1-16)"
CACHE_ROOT="${GMS_FFMPEG_CACHE:-$HOME/.cache/gms-ffmpeg-program}"
CACHE_KEY="${RECIPE_ID}-${TARGET}-${VARIANT}"
CACHE_ENTRY="$CACHE_ROOT/$CACHE_KEY"
PREFIX="$CACHE_ENTRY/prefix"

WORK="$(mktemp -d)"
trap 'rm -rf "$WORK"' EXIT
DL="$WORK/dl"
mkdir -p "$DL"

# ---------------------------------------------------------------------------
# Cross-build isolation: a mingw build must only ever see OUR freshly-built
# .pc files, never the Linux host's, or it would silently link a native .so
# into a mingw object and fail at link time (or worse, "succeed" against the
# wrong ABI) - PKG_CONFIG_LIBDIR, which REPLACES the default search path,
# below. The native Linux build instead ADDS our prefix on top of the host's
# normal pkg-config behaviour (PKG_CONFIG_PATH) - it still needs the system's
# own .pc files, e.g. libva (built from source into PREFIX) depends on
# libdrm via pkg-config, and libdrm itself is only ever apt-installed, never
# built into PREFIX.
# ---------------------------------------------------------------------------

if [ "$MINGW" = "1" ]; then
  # LIBDIR *replaces* the default search path - exactly what a cross build
  # needs, so a mingw configure step can never resolve a native x86_64-linux
  # .pc file and link the wrong ABI.
  export PKG_CONFIG_LIBDIR="$PREFIX/lib/pkgconfig"
else
  # PATH *adds to* the default search path. The native Linux build still
  # needs the system's own .pc files - libva (built from source into
  # PREFIX) depends on libdrm via pkg-config, and libdrm itself is only
  # ever apt-installed (APT_DEPS_LINUX), never built into PREFIX. An
  # earlier version of this script used LIBDIR unconditionally here, which
  # hid every system .pc file including libdrm's and broke libva's own
  # configure step.
  export PKG_CONFIG_PATH="$PREFIX/lib/pkgconfig"
fi
export PKG_CONFIG="pkg-config"
# --static below makes autotools/meson/cmake dependency probes request the
# static .a; without it some probes pick up a shared lib that doesn't exist
# in our deps-only prefix.
export PKG_CONFIG_FLAGS="--static"

CC="${CROSS}gcc"
CXX="${CROSS}g++"
AR="${CROSS}ar"
RANLIB="${CROSS}ranlib"
STRIP="${CROSS}strip"
if [ "$MINGW" = "1" ]; then
  WINDRES="${CROSS}windres"
fi

# A toolchain file for the cmake-based deps (x265, SVT-AV1, libwebp, libvpl).
# Native Linux build passes no -DCMAKE_TOOLCHAIN_FILE at all.
CMAKE_TOOLCHAIN=""
# A cross file for the meson-based deps (dav1d, fribidi, HarfBuzz).
MESON_CROSS=""
if [ "$MINGW" = "1" ]; then
  CMAKE_TOOLCHAIN="$WORK/mingw-toolchain.cmake"
  cat > "$CMAKE_TOOLCHAIN" <<EOF
set(CMAKE_SYSTEM_NAME Windows)
set(CMAKE_SYSTEM_PROCESSOR x86_64)
set(CMAKE_C_COMPILER ${CC})
set(CMAKE_CXX_COMPILER ${CXX})
set(CMAKE_RC_COMPILER ${WINDRES})
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
EOF
  MESON_CROSS="$WORK/mingw-cross.ini"
  cat > "$MESON_CROSS" <<EOF
[binaries]
c = '${CC}'
cpp = '${CXX}'
ar = '${AR}'
strip = '${STRIP}'
windres = '${WINDRES}'
pkg-config = 'pkg-config'

[host_machine]
system = 'windows'
cpu_family = 'x86_64'
cpu = 'x86_64'
endian = 'little'
EOF
fi

# ---------------------------------------------------------------------------
# Generic per-build-system wrappers. Every *_build() function below extracts
# into $WORK/src/<name> and installs into the shared $PREFIX.
# ---------------------------------------------------------------------------

# autotools_build name tarball sha256 strip configure-extra-args...
autotools_build() {
  local name="$1" tarball="$2" sha256="$3" strip="$4"; shift 4
  local tgz src
  tgz="$DL/$(basename "$tarball")"
  src="$WORK/src/$name"
  fetch_pinned "$tarball" "$sha256" "$tgz"
  extract_src "$tgz" "$src" "$strip"
  if [ ! -x "$src/configure" ]; then
    say "$name: no pre-generated configure - running autoreconf"
    logged "$name-autoreconf" env -C "$src" autoreconf -fiv
  fi
  local hostargs=()
  [ "$MINGW" = "1" ] && hostargs=(--host="$HOST_TRIPLE")
  logged "$name-configure" env -C "$src" ./configure \
    --prefix="$PREFIX" --enable-static --disable-shared \
    CC="$CC" CXX="$CXX" AR="$AR" RANLIB="$RANLIB" STRIP="$STRIP" \
    PKG_CONFIG="$PKG_CONFIG" \
    "${hostargs[@]}" "$@"
  logged "$name-build" make -C "$src" -j"$JOBS"
  logged "$name-install" make -C "$src" install
}

# cmake_build name tarball sha256 strip cmake-source-subdir cmake-extra-args...
cmake_build() {
  local name="$1" tarball="$2" sha256="$3" strip="$4" subdir="$5"; shift 5
  local tgz src build
  tgz="$DL/$(basename "$tarball")"
  src="$WORK/src/$name"
  build="$WORK/build/$name"
  fetch_pinned "$tarball" "$sha256" "$tgz"
  extract_src "$tgz" "$src" "$strip"
  local toolchain_args=()
  [ -n "$CMAKE_TOOLCHAIN" ] && toolchain_args=(-DCMAKE_TOOLCHAIN_FILE="$CMAKE_TOOLCHAIN")
  logged "$name-configure" cmake -S "$src/$subdir" -B "$build" -G Ninja \
    -DCMAKE_BUILD_TYPE=Release \
    -DCMAKE_INSTALL_PREFIX="$PREFIX" \
    -DCMAKE_PREFIX_PATH="$PREFIX" \
    -DBUILD_SHARED_LIBS=OFF \
    "${toolchain_args[@]}" "$@"
  logged "$name-build" cmake --build "$build" -j"$JOBS"
  logged "$name-install" cmake --install "$build"
}

# meson_build name tarball sha256 strip meson-extra-args...
meson_build() {
  local name="$1" tarball="$2" sha256="$3" strip="$4"; shift 4
  local tgz src build
  tgz="$DL/$(basename "$tarball")"
  src="$WORK/src/$name"
  build="$WORK/build/$name"
  fetch_pinned "$tarball" "$sha256" "$tgz"
  extract_src "$tgz" "$src" "$strip"
  local cross_args=()
  [ -n "$MESON_CROSS" ] && cross_args=(--cross-file="$MESON_CROSS")
  logged "$name-configure" meson setup "$build" "$src" \
    --prefix="$PREFIX" --libdir=lib --buildtype=release \
    --default-library=static \
    "${cross_args[@]}" "$@"
  logged "$name-build" ninja -C "$build" -j"$JOBS"
  logged "$name-install" ninja -C "$build" install
}

# ---------------------------------------------------------------------------
# One function per dependency. Each is a thin call into the generic
# wrappers above, except the handful of projects with their own configure
# conventions (zlib, libvpx, x264) which get bespoke functions.
# ---------------------------------------------------------------------------

build_zlib() {
  local tgz="$DL/zlib-${ZLIB_VERSION}.tar.gz" src="$WORK/src/zlib"
  fetch_pinned "$ZLIB_URL" "$ZLIB_SHA256" "$tgz"
  extract_src "$tgz" "$src" 1
  logged zlib-configure env -C "$src" CC="$CC" AR="$AR" RANLIB="$RANLIB" \
    ./configure --prefix="$PREFIX" --static
  logged zlib-build make -C "$src" -j"$JOBS"
  logged zlib-install make -C "$src" install
}

# Headers + a .pc file only - FFmpeg dlopens the NVIDIA driver's own
# nvcuda/nvEncodeAPI/libnvidia-encode at RUNTIME (--enable-ffnvcodec),
# nothing NVIDIA-owned is compiled or linked in here.
build_nvcodecheaders() {
  local tgz="$DL/nv-codec-headers-${NVHEADERS_VERSION}.tar.gz" src="$WORK/src/nv-codec-headers"
  fetch_pinned "$NVHEADERS_URL" "$NVHEADERS_SHA256" "$tgz"
  extract_src "$tgz" "$src" 1
  logged nvcodec-install make -C "$src" install PREFIX="$PREFIX"
}

build_libvpl() {
  cmake_build libvpl "$LIBVPL_URL" "$LIBVPL_SHA256" 1 "." \
    -DBUILD_TOOLS=OFF -DBUILD_EXAMPLES=OFF -DBUILD_TESTS=OFF \
    -DINSTALL_EXAMPLE_CODE=OFF
}

# Linux only (VAAPI). Deliberately no X11/Wayland/GLX backend - GMS reaches
# VAAPI through DRM render nodes for hwaccel transcode, never through a
# window system.
build_libva() {
  autotools_build libva "$LIBVA_URL" "$LIBVA_SHA256" 1 \
    --disable-docs --enable-drm --disable-x11 --disable-wayland --disable-glx
}

build_dav1d() {
  meson_build dav1d "$DAV1D_URL" "$DAV1D_SHA256" 1 \
    -Denable_tools=false -Denable_tests=false -Denable_docs=false
}

build_libaom() {
  cmake_build libaom "$AOM_URL" "$AOM_SHA256" 1 "." \
    -DENABLE_DOCS=0 -DENABLE_EXAMPLES=0 -DENABLE_TESTS=0 -DENABLE_TOOLS=0 \
    -DENABLE_NASM=1 -DCONFIG_AV1_HIGHBITDEPTH=1
}

build_svtav1() {
  local tarpath="$DL/SVT-AV1-${SVTAV1_TAG}.tar.gz"
  fetch_git_archive svt-av1 "$SVTAV1_REPO" "$SVTAV1_TAG" "$SVTAV1_COMMIT" "$SVTAV1_SHA256" \
    "$tarpath" "SVT-AV1-${SVTAV1_TAG}"
  cmake_build svt-av1 "$tarpath" "$SVTAV1_SHA256" 1 "." \
    -DBUILD_APPS=OFF -DBUILD_DEC=ON -DBUILD_ENC=ON -DENABLE_NASM=ON
}

# Kvazaar (HEVC) - the processor fallback encoder when no graphics-card
# encoder is available (#816). Ships a real release tarball (see the pin
# comment), so this is a plain cmake_build call like libaom/libwebp above -
# no git-archive needed. BUILD_SHARED_LIBS=OFF is cmake_build's own default;
# the rest just turns off everything we don't ship (the kvazaar-bin CLI,
# its test suite, an optional crypto dependency neither variant needs).
build_kvazaar() {
  cmake_build kvazaar "$KVAZAAR_URL" "$KVAZAAR_SHA256" 1 "." \
    -DBUILD_TESTS=OFF -DBUILD_KVAZAAR_BINARY=OFF -DUSE_CRYPTO=OFF
  # Overwrite kvazaar's own generated kvazaar.pc with a minimal, direct one -
  # every field FFmpeg's require_pkg_config actually reads, nothing its own
  # template adds that we need (its CLI tool's man page, which we don't
  # build). -DKVZ_STATIC_LIB is the real fix for the win-x64 cross-build
  # failure (runs 36962718265, 36965945105): kvazaar.h's KVZ_PUBLIC macro
  # defaults to __declspec(dllimport) on Windows unless the CONSUMER defines
  # KVZ_STATIC_LIB, so FFmpeg's plain -I/-l pkg-config consumption (no CMake
  # target, so no automatic propagation of kvazaar's own build-time defines)
  # linked against our static libkvazaar.a expecting an import-table symbol
  # (__imp_kvz_api_get) that only exists for a DLL - "undefined reference to
  # `__imp_kvz_api_get'" at link time, confirmed via the kvazaar.pc dump
  # show_pc() below added to this run's log: the .pc file itself was already
  # correct (Version 2.3.2, right Libs/Cflags) - only the static-vs-DLL
  # macro was missing. Linux doesn't need it (KVZ_PUBLIC is a no-op there).
  # -lpthread (run 37006644547): kvazaar's threadqueue.c calls pthread_*
  # directly even under mingw (relying on winpthreads) - Linux glibc links
  # pthread symbols into libc itself (2.34+) so this only bites the cross
  # build, same reasoning as KVZ_STATIC_LIB above.
  mkdir -p "$PREFIX/lib/pkgconfig"
  cat > "$PREFIX/lib/pkgconfig/kvazaar.pc" <<EOF
prefix=$PREFIX
libdir=\${prefix}/lib
includedir=\${prefix}/include

Name: libkvazaar
Description: An open-source HEVC encoder
Version: $KVAZAAR_VERSION
Libs: -L\${libdir} -lkvazaar -lpthread
Cflags: -I\${includedir} -DKVZ_STATIC_LIB
EOF
}

# Post-build visibility for a dependency whose own install() rules produce
# a pkg-config file this script doesn't fully control (unlike
# build_kvazaar's direct override above) - printed unconditionally, win or
# lose, so a cross-compile-only pkg-config miss shows its actual content in
# THIS run's log instead of costing another guess-and-push round.
show_pc() { # name
  local f="$PREFIX/lib/pkgconfig/$1.pc"
  if [ -f "$f" ]; then
    say "$1.pc ($f):"
    cat "$f" >&2
  else
    say "$1.pc: MISSING at $f"
    ls -la "$PREFIX/lib/pkgconfig/" >&2 2>/dev/null || true
  fi
}

# libvpx's own configure predates autoconf conventions: --target=<arch>-<os>-<cc>
# instead of --host, and CROSS= for the toolchain prefix.
build_libvpx() {
  local tgz="$DL/libvpx-${VPX_VERSION}.tar.gz" src="$WORK/src/libvpx"
  fetch_pinned "$VPX_URL" "$VPX_SHA256" "$tgz"
  extract_src "$tgz" "$src" 1
  local vpx_target="x86_64-linux-gcc"
  [ "$MINGW" = "1" ] && vpx_target="x86_64-win64-gcc"
  logged libvpx-configure env -C "$src" \
    CC="$CC" CXX="$CXX" AR="$AR" RANLIB="$RANLIB" STRIP="$STRIP" CROSS="$CROSS" \
    ./configure --prefix="$PREFIX" --target="$vpx_target" \
    --disable-examples --disable-tools --disable-docs --disable-unit-tests \
    --disable-shared --enable-static --enable-pic --as=nasm \
    --enable-vp9-highbitdepth
  logged libvpx-build make -C "$src" -j"$JOBS"
  logged libvpx-install make -C "$src" install
}

# OpenH264 (H.264) - the processor fallback encoder when no graphics-card
# encoder is available (#816). Predates autoconf/cmake conventions too, like
# libvpx above: its own hand-rolled top-level Makefile selects a platform
# file via OS=<name> (build/platform-<OS>.mk - "linux" autodetects via
# uname, "mingw_nt" must be given explicitly for the cross build) and
# ARCH=x86_64, with CC/CXX/AR/STRIP as plain make command-line overrides,
# never configure flags. `libopenh264.a` is the exact static-lib make
# target (LIBPREFIX=lib + PROJECT_NAME=openh264 + LIBSUFFIX=a, all fixed by
# the top Makefile regardless of OS) - built explicitly rather than the
# generic `libraries` target, which would also build the shared .so/.dll
# this build never uses. `install-static` installs that lib, its headers,
# and an openh264.pc pkg-config file - FFmpeg's configure resolves
# libopenh264 via pkg-config (require_pkg_config), same as kvazaar above.
build_openh264() {
  local tarpath="$DL/openh264-${OPENH264_TAG}.tar.gz" src="$WORK/src/openh264"
  fetch_git_archive openh264 "$OPENH264_REPO" "$OPENH264_TAG" "$OPENH264_COMMIT" "$OPENH264_SHA256" \
    "$tarpath" "openh264-${OPENH264_TAG}"
  extract_src "$tarpath" "$src" 1
  local os_name="linux"
  [ "$MINGW" = "1" ] && os_name="mingw_nt"
  local mkargs=(OS="$os_name" ARCH=x86_64 CC="$CC" CXX="$CXX" AR="$AR" STRIP="$STRIP" PREFIX="$PREFIX")
  logged openh264-build make -C "$src" -j"$JOBS" "${mkargs[@]}" libopenh264.a
  logged openh264-install make -C "$src" "${mkargs[@]}" install-static
}

build_opus() {
  autotools_build opus "$OPUS_URL" "$OPUS_SHA256" 1 \
    --disable-doc --disable-extra-programs
}

build_zimg() {
  autotools_build zimg "$ZIMG_URL" "$ZIMG_SHA256" 1
}

build_libwebp() {
  cmake_build libwebp "$WEBP_URL" "$WEBP_SHA256" 1 "." \
    -DWEBP_BUILD_ANIM_UTILS=OFF -DWEBP_BUILD_CWEBP=OFF -DWEBP_BUILD_DWEBP=OFF \
    -DWEBP_BUILD_GIF2WEBP=OFF -DWEBP_BUILD_IMG2WEBP=OFF -DWEBP_BUILD_VWEBP=OFF \
    -DWEBP_BUILD_WEBPINFO=OFF -DWEBP_BUILD_LIBWEBPMUX=ON -DWEBP_BUILD_EXTRAS=OFF
}

# No harfbuzz here (would create a freetype<->harfbuzz build-order cycle;
# harfbuzz's freetype integration is optional and only improves autohinting,
# which GMS's one subtitle-preview burn-in filter does not depend on).
build_freetype() {
  autotools_build freetype "$FREETYPE_URL" "$FREETYPE_SHA256" 1 \
    --without-harfbuzz --without-png --without-bzip2 --without-brotli \
    --with-zlib=yes
}

build_fribidi() {
  meson_build fribidi "$FRIBIDI_URL" "$FRIBIDI_SHA256" 1 \
    -Ddocs=false -Dtests=false -Dbin=false
}

# No freetype/glib/icu/cairo - libass is the only consumer here and only
# needs HarfBuzz's text-shaping, not its (optional) glyph rendering paths.
build_harfbuzz() {
  meson_build harfbuzz "$HARFBUZZ_URL" "$HARFBUZZ_SHA256" 1 \
    -Dfreetype=disabled -Dglib=disabled -Dgobject=disabled -Dicu=disabled \
    -Dtests=disabled -Ddocs=disabled -Dutilities=disabled -Dcairo=disabled
}

# Linux only - fontconfig's XML config parser (fonts.conf, conf.d/*.conf).
# Standard autotools project; the generic wrapper is all it needs.
# libass's line-breaking library. Optional to libass and auto-detected, which
# is how r1-r3 shipped a program that needed the BUILD HOST's shared
# libunibreak.so.5: libass found the runner's libunibreak-dev, and the
# program failed on a clean machine with "cannot open shared object file"
# (#803, found in the clean-room container 2026-10-05). Built here, static,
# before libass, so libass links this copy and the program needs only glibc
# and the GCC runtime from the host - what check_appimage_ffmpeg_program.sh
# verifies with readelf on every build.
build_libunibreak() {
  autotools_build libunibreak "$UNIBREAK_URL" "$UNIBREAK_SHA256" 1
}

build_expat() {
  autotools_build expat "$EXPAT_URL" "$EXPAT_SHA256" 1 \
    --without-xmlwf --without-examples --without-tests --without-docbook
}

# Linux only - libass's system font provider (see the FONTCONFIG_VERSION pin
# comment above and build_libass() below). Bespoke, not autotools_build():
# --sysconfdir=/etc --localstatedir=/var bakes in the END USER's real
# config/cache paths as compiled-in defaults, so a plain `make install`
# would try to write INTO this build host's actual /etc and /var - which it
# has no permission to do (install_deps()'s passwordless sudo covers
# apt-get only) and must never do anyway, since this runner's /etc/fonts is
# irrelevant to what ships. DESTDIR stages the whole tree instead; only the
# $PREFIX-rooted slice (headers, the static lib, the .pc file) is merged
# into the real $PREFIX afterward, and the staged /etc + /var are discarded
# with it.
build_fontconfig() {
  local tgz="$DL/fontconfig-${FONTCONFIG_VERSION}.tar.xz" src="$WORK/src/fontconfig"
  fetch_pinned "$FONTCONFIG_URL" "$FONTCONFIG_SHA256" "$tgz"
  extract_src "$tgz" "$src" 1
  logged fontconfig-configure env -C "$src" ./configure \
    --prefix="$PREFIX" --enable-static --disable-shared \
    --sysconfdir=/etc --localstatedir=/var \
    --disable-docs --disable-docbook --disable-nls --disable-cache-build \
    CC="$CC" CXX="$CXX" AR="$AR" RANLIB="$RANLIB" STRIP="$STRIP" \
    PKG_CONFIG="$PKG_CONFIG"
  logged fontconfig-build make -C "$src" -j"$JOBS"
  local stage="$WORK/destdir-fontconfig"
  logged fontconfig-install make -C "$src" install DESTDIR="$stage"
  cp -a "$stage$PREFIX/." "$PREFIX/"
}

# Linux: fontconfig (built just above) is libass's system font provider, so
# a static ffmpeg still finds the end user's own fonts at run time - this is
# what fixes the "No system font provider!" configure failure (run
# 36816406247) without reaching for --disable-require-system-font-provider,
# which the brief rules out because GMS needs real subtitle-burn-in font
# rendering (lib/services/subtitle/timeshift_service.dart). Windows needs no
# library here - DirectWrite (detected via plain <windows.h> + -lgdi32, both
# already present in every mingw-w64 install) is libass's provider there.
build_libass() {
  local font_flags=()
  if [ "$MINGW" = "1" ]; then
    font_flags=(--disable-fontconfig)
  else
    font_flags=(--enable-fontconfig)
  fi
  # --enable-libunibreak (not the default "check") makes configure FAIL if
  # libass cannot find our static libunibreak, instead of silently building
  # without line breaking or, worse, against a shared one from the host.
  autotools_build libass "$LIBASS_URL" "$LIBASS_SHA256" 1 "${font_flags[@]}" \
    --enable-libunibreak
  want_define "$WORK/src/libass/config.h" CONFIG_UNIBREAK 1
  # autoheader only emits a literal `#define NAME 1` when the provider was
  # actually found (the disabled case stays a commented-out `/* #undef */`,
  # unlike FFmpeg's own config.h elsewhere in this script), so want_define
  # is only meaningful in the "must be found" direction - which is exactly
  # the silent-failure mode this script's want_define pattern exists to
  # catch: a libass that silently built without a font provider would still
  # link into ffmpeg fine and only fail at subtitle-burn-in runtime.
  if [ "$MINGW" = "1" ]; then
    want_define "$WORK/src/libass/config.h" CONFIG_DIRECTWRITE 1
  else
    want_define "$WORK/src/libass/config.h" CONFIG_FONTCONFIG 1
  fi
}

# Windows only. Headers only (AMD's own lightweight release asset, not
# their full SDK repo) - same dlopen-at-runtime model as nv-codec-headers;
# FFmpeg loads amfrt64.dll from whatever AMD driver is on the machine.
# Sets AMF_HEADERS_DIR for the ffmpeg configure step below.
AMF_HEADERS_DIR=""
build_amf_headers() {
  local tgz="$DL/AMF-headers-${AMF_VERSION}.tar.gz"
  fetch_pinned "$AMF_URL" "$AMF_SHA256" "$tgz"
  AMF_HEADERS_DIR="$WORK/src/amf-headers"
  extract_src "$tgz" "$AMF_HEADERS_DIR" 1
}

# ---- gpl-variant-only (GPL-2.0-or-later) ----

build_x264() {
  local tgz="$DL/x264-${X264_REF}.tar.gz" src="$WORK/src/x264"
  fetch_git_archive x264 "$X264_REPO" "" "$X264_REF" "$X264_SHA256" "$tgz" "x264-${X264_REF}"
  extract_src "$tgz" "$src" 1
  local hostargs=()
  [ "$MINGW" = "1" ] && hostargs=(--host="$HOST_TRIPLE" --cross-prefix="$CROSS")
  logged x264-configure env -C "$src" \
    ./configure --prefix="$PREFIX" --enable-static --disable-cli \
    --disable-opencl --enable-pic "${hostargs[@]}"
  logged x264-build make -C "$src" -j"$JOBS"
  logged x264-install make -C "$src" install
}

build_x265() {
  cmake_build x265 "$X265_URL" "$X265_SHA256" 1 "source" \
    -DENABLE_CLI=OFF -DENABLE_TESTS=OFF -DENABLE_ASSEMBLY=ON
}

# ---------------------------------------------------------------------------
# FFmpeg itself.
# ---------------------------------------------------------------------------

build_ffmpeg() {
  local tgz="$DL/ffmpeg-${FFMPEG_VERSION}.tar.xz" src="$WORK/src/ffmpeg"
  fetch_pinned "$FFMPEG_URL" "$FFMPEG_SHA256" "$tgz"
  curl -fsSL --retry 3 --retry-delay 3 -o "$tgz.asc" "$FFMPEG_URL.asc" \
    || die "download failed: $FFMPEG_URL.asc"
  (
    GNUPGHOME="$WORK/gnupg"
    export GNUPGHOME
    mkdir -p "$GNUPGHOME" && chmod 700 "$GNUPGHOME"
    curl -fsSL --retry 3 -o "$WORK/ffmpeg-devel.asc" https://ffmpeg.org/ffmpeg-devel.asc
    gpg --batch --quiet --import "$WORK/ffmpeg-devel.asc" 2>/dev/null
    fpr="$(gpg --batch --with-colons --fingerprint | awk -F: '$1=="fpr"{print $10; exit}')"
    [ "$fpr" = "$FFMPEG_KEY_FPR" ] || die "ffmpeg.org served key $fpr, expected $FFMPEG_KEY_FPR"
    gpg --batch --quiet --verify "$tgz.asc" "$tgz" 2>/dev/null \
      || die "FFmpeg $FFMPEG_VERSION signature does not verify"
  )
  extract_src "$tgz" "$src" 1

  local extra_cflags="-I$PREFIX/include"
  local extra_ldflags="-L$PREFIX/lib"
  # Static C++ dependencies (libvpl, zimg) need the C++ runtime on every link
  # FFmpeg's configure tests, and their .pc files do not all list it.
  local extra_libs="-lstdc++ -lm -lpthread -ldl"
  [ "$MINGW" = "1" ] && extra_libs="-lstdc++"
  local plat_flags=()
  if [ "$MINGW" = "1" ]; then
    extra_cflags="$extra_cflags -I$AMF_HEADERS_DIR"
    # -static: the one flag that makes the mingw cross-build need no
    # libwinpthread-1.dll / libgcc_s_seh-1.dll / libstdc++-6.dll alongside
    # it - "need no extra DLLs" from the brief.
    extra_ldflags="$extra_ldflags -static"
    plat_flags=(
      --enable-amf --enable-d3d11va --enable-dxva2
      --arch=x86_64 --target-os=mingw32
      --cross-prefix="$CROSS" --enable-cross-compile
    )
  else
    plat_flags=(--enable-vaapi)
  fi

  local variant_flags=()
  [ "$VARIANT" = "gpl" ] && variant_flags=(--enable-gpl --enable-libx264 --enable-libx265)

  ffmpeg_configure env -C "$src" ./configure \
    --prefix="$PREFIX" \
    --pkg-config=pkg-config --pkg-config-flags=--static \
    --extra-cflags="$extra_cflags" --extra-ldflags="$extra_ldflags" \
    --extra-libs="$extra_libs" \
    --cc="$CC" --cxx="$CXX" --ar="$AR" --ranlib="$RANLIB" --strip="$STRIP" \
    --enable-static --disable-shared --enable-pic \
    --disable-debug --disable-doc --disable-ffplay \
    --disable-autodetect --disable-network \
    --enable-pthreads --disable-w32threads \
    --enable-zlib \
    --enable-libopus --enable-libdav1d --enable-libsvtav1 \
    --enable-libaom --enable-libvpx --enable-libzimg --enable-libwebp \
    --enable-libass --enable-libfreetype --enable-libfribidi \
    --enable-ffnvcodec --enable-nvenc --enable-nvdec --enable-cuvid \
    --enable-libvpl \
    --enable-libkvazaar --enable-libopenh264 \
    "${plat_flags[@]}" "${variant_flags[@]}"

  # Assert the variant contract + every inventoried capability actually
  # compiled in - see the file header for why this isn't optional.
  local h="$src/config.h"
  want_define "$h" CONFIG_NONFREE 0
  if [ "$VARIANT" = "gpl" ]; then
    want_define "$h" CONFIG_GPL 1
    want_define "$h" CONFIG_LIBX264 1
    want_define "$h" CONFIG_LIBX265 1
  else
    want_define "$h" CONFIG_GPL 0
    want_define "$h" CONFIG_LIBX264 0
    want_define "$h" CONFIG_LIBX265 0
  fi
  local f
  for f in CONFIG_ZLIB CONFIG_LIBOPUS CONFIG_LIBDAV1D CONFIG_LIBSVTAV1 \
           CONFIG_LIBAOM CONFIG_LIBVPX CONFIG_LIBZIMG CONFIG_LIBWEBP \
           CONFIG_LIBASS CONFIG_LIBFREETYPE CONFIG_LIBFRIBIDI \
           CONFIG_FFNVCODEC CONFIG_NVENC CONFIG_NVDEC CONFIG_CUVID \
           CONFIG_LIBVPL CONFIG_LIBKVAZAAR CONFIG_LIBOPENH264; do
    want_define "$h" "$f" 1
  done
  if [ "$MINGW" = "1" ]; then
    for f in CONFIG_AMF CONFIG_D3D11VA CONFIG_DXVA2; do want_define "$h" "$f" 1; done
  else
    want_define "$h" CONFIG_VAAPI 1
  fi

  say "building FFmpeg $FFMPEG_VERSION ($JOBS jobs)"
  logged ffmpeg-build make -C "$src" -j"$JOBS"
  logged ffmpeg-install make -C "$src" install
}

# Fetch (sha256-verified, no compilation) every tarball this (target,variant)
# needs, regardless of cache status - the Corresponding Source bundle must
# be complete even when the compiled PREFIX comes straight from cache.
# Cheap: ~18 small-to-medium HTTPS downloads, a minute or two at most.
fetch_all_sources() {
  fetch_pinned "$ZLIB_URL" "$ZLIB_SHA256" "$DL/zlib-${ZLIB_VERSION}.tar.gz"
  fetch_pinned "$NVHEADERS_URL" "$NVHEADERS_SHA256" "$DL/nv-codec-headers-${NVHEADERS_VERSION}.tar.gz"
  fetch_pinned "$LIBVPL_URL" "$LIBVPL_SHA256" "$DL/libvpl-${LIBVPL_VERSION}.tar.gz"
  if [ "$MINGW" = "1" ]; then
    fetch_pinned "$AMF_URL" "$AMF_SHA256" "$DL/AMF-headers-${AMF_VERSION}.tar.gz"
  else
    fetch_pinned "$LIBVA_URL" "$LIBVA_SHA256" "$DL/libva-${LIBVA_VERSION}.tar.bz2"
  fi
  fetch_pinned "$DAV1D_URL" "$DAV1D_SHA256" "$DL/dav1d-${DAV1D_VERSION}.tar.xz"
  fetch_pinned "$AOM_URL" "$AOM_SHA256" "$DL/libaom-${AOM_VERSION}.tar.gz"
  aom_verify_signature "$DL/libaom-${AOM_VERSION}.tar.gz"
  fetch_git_archive svt-av1 "$SVTAV1_REPO" "$SVTAV1_TAG" "$SVTAV1_COMMIT" "$SVTAV1_SHA256" \
    "$DL/SVT-AV1-${SVTAV1_TAG}.tar.gz" "SVT-AV1-${SVTAV1_TAG}"
  fetch_pinned "$VPX_URL" "$VPX_SHA256" "$DL/libvpx-${VPX_VERSION}.tar.gz"
  fetch_pinned "$KVAZAAR_URL" "$KVAZAAR_SHA256" "$DL/kvazaar-${KVAZAAR_VERSION}.tar.gz"
  fetch_git_archive openh264 "$OPENH264_REPO" "$OPENH264_TAG" "$OPENH264_COMMIT" "$OPENH264_SHA256" \
    "$DL/openh264-${OPENH264_TAG}.tar.gz" "openh264-${OPENH264_TAG}"
  fetch_pinned "$OPUS_URL" "$OPUS_SHA256" "$DL/opus-${OPUS_VERSION}.tar.gz"
  fetch_pinned "$ZIMG_URL" "$ZIMG_SHA256" "$DL/zimg-${ZIMG_VERSION}.tar.gz"
  fetch_pinned "$WEBP_URL" "$WEBP_SHA256" "$DL/libwebp-${WEBP_VERSION}.tar.gz"
  fetch_pinned "$FREETYPE_URL" "$FREETYPE_SHA256" "$DL/freetype-${FREETYPE_VERSION}.tar.xz"
  fetch_pinned "$FRIBIDI_URL" "$FRIBIDI_SHA256" "$DL/fribidi-${FRIBIDI_VERSION}.tar.xz"
  fetch_pinned "$HARFBUZZ_URL" "$HARFBUZZ_SHA256" "$DL/harfbuzz-${HARFBUZZ_VERSION}.tar.xz"
  fetch_pinned "$UNIBREAK_URL" "$UNIBREAK_SHA256" "$DL/libunibreak-${UNIBREAK_VERSION}.tar.gz"
  if [ "$MINGW" != "1" ]; then
    fetch_pinned "$EXPAT_URL" "$EXPAT_SHA256" "$DL/expat-${EXPAT_VERSION}.tar.xz"
    fetch_pinned "$FONTCONFIG_URL" "$FONTCONFIG_SHA256" "$DL/fontconfig-${FONTCONFIG_VERSION}.tar.xz"
  fi
  fetch_pinned "$LIBASS_URL" "$LIBASS_SHA256" "$DL/libass-${LIBASS_VERSION}.tar.gz"
  if [ "$VARIANT" = "gpl" ]; then
    fetch_git_archive x264 "$X264_REPO" "" "$X264_REF" "$X264_SHA256" \
      "$DL/x264-${X264_REF}.tar.gz" "x264-${X264_REF}"
    fetch_pinned "$X265_URL" "$X265_SHA256" "$DL/x265-${X265_VERSION}.tar.gz"
  fi
  fetch_pinned "$FFMPEG_URL" "$FFMPEG_SHA256" "$DL/ffmpeg-${FFMPEG_VERSION}.tar.xz"
  curl -fsSL --retry 3 --retry-delay 3 -o "$DL/ffmpeg-${FFMPEG_VERSION}.tar.xz.asc" "$FFMPEG_URL.asc" \
    || die "download failed: $FFMPEG_URL.asc"
}

build_all() {
  build_zlib
  build_nvcodecheaders
  build_libvpl
  if [ "$MINGW" = "1" ]; then
    build_amf_headers
  else
    build_libva
  fi
  build_dav1d
  build_libaom
  build_svtav1
  build_kvazaar
  show_pc kvazaar
  build_libvpx
  build_openh264
  show_pc openh264
  build_opus
  build_zimg
  build_libwebp
  build_freetype
  build_fribidi
  build_harfbuzz
  build_libunibreak
  if [ "$MINGW" != "1" ]; then
    build_expat
    build_fontconfig
  fi
  build_libass
  if [ "$VARIANT" = "gpl" ]; then
    build_x264
    build_x265
  fi
  build_ffmpeg
}

# ---------------------------------------------------------------------------
# scripts/release/ffmpeg_components.json - invocation-independent (always
# the full pin set, not just what this (target,variant) call built), so one
# run keeps the notices generator's input current regardless of which
# combination triggered it. Plain JSON, no "schema" field by design (task
# brief) - this is a generated sidecar for another worker's tool, not a
# CLAUDE.md Sec4 exportable artifact.
# ---------------------------------------------------------------------------

write_components_json() {
  local out="$REPO_ROOT/scripts/release/ffmpeg_components.json"
  local gpl_only='"x264", "x265"'
  # Generated from COMMON_COMPONENT_NAMES (defined alongside the pins above)
  # instead of its own literal, so this file and collect_licenses() can
  # never name a component's set differently.
  local common_names
  common_names="$(printf '"%s", ' "${COMMON_COMPONENT_NAMES[@]}")"
  common_names="${common_names%, }"
  cat > "$out" <<EOF
{
  "ffmpeg": "$FFMPEG_VERSION",
  "variants": {
    "gpl": ["ffmpeg", $gpl_only, $common_names],
    "lgpl": ["ffmpeg", $common_names]
  },
  "components": [
    {"name": "ffmpeg", "version": "$FFMPEG_VERSION", "license": "GPL-2.0-or-later (gpl variant) OR LGPL-2.1-or-later (lgpl variant)", "url": "$FFMPEG_URL", "sha256": "$FFMPEG_SHA256"},
    {"name": "x264", "version": "$X264_REF", "license": "GPL-2.0-or-later", "url": "$X264_REPO (commit $X264_REF, fetched by git - no stable release tarball exists)", "sha256": "$X264_SHA256"},
    {"name": "x265", "version": "$X265_VERSION", "license": "GPL-2.0-or-later", "url": "$X265_URL", "sha256": "$X265_SHA256"},
    {"name": "svt-av1", "version": "$SVTAV1_TAG", "license": "BSD-2-Clause-Patent", "url": "$SVTAV1_REPO (tag $SVTAV1_TAG, commit $SVTAV1_COMMIT, fetched by git - no stable release tarball exists)", "sha256": "$SVTAV1_SHA256"},
    {"name": "kvazaar", "version": "$KVAZAAR_VERSION", "license": "BSD-3-Clause", "url": "$KVAZAAR_URL", "sha256": "$KVAZAAR_SHA256"},
    {"name": "libaom", "version": "$AOM_VERSION", "license": "BSD-2-Clause AND AOM-Patent-1.0", "url": "$AOM_URL", "sha256": "$AOM_SHA256"},
    {"name": "libvpx", "version": "$VPX_VERSION", "license": "BSD-3-Clause", "url": "$VPX_URL", "sha256": "$VPX_SHA256"},
    {"name": "openh264", "version": "$OPENH264_TAG", "license": "BSD-2-Clause", "url": "$OPENH264_REPO (tag $OPENH264_TAG, commit $OPENH264_COMMIT, fetched by git - no release source asset exists)", "sha256": "$OPENH264_SHA256"},
    {"name": "libopus", "version": "$OPUS_VERSION", "license": "BSD-3-Clause", "url": "$OPUS_URL", "sha256": "$OPUS_SHA256"},
    {"name": "dav1d", "version": "$DAV1D_VERSION", "license": "BSD-2-Clause", "url": "$DAV1D_URL", "sha256": "$DAV1D_SHA256"},
    {"name": "zimg", "version": "$ZIMG_VERSION", "license": "WTFPL", "url": "$ZIMG_URL", "sha256": "$ZIMG_SHA256"},
    {"name": "libwebp", "version": "$WEBP_VERSION", "license": "BSD-3-Clause", "url": "$WEBP_URL", "sha256": "$WEBP_SHA256"},
    {"name": "libass", "version": "$LIBASS_VERSION", "license": "ISC", "url": "$LIBASS_URL", "sha256": "$LIBASS_SHA256"},
    {"name": "freetype", "version": "$FREETYPE_VERSION", "license": "FTL", "url": "$FREETYPE_URL", "sha256": "$FREETYPE_SHA256"},
    {"name": "fribidi", "version": "$FRIBIDI_VERSION", "license": "LGPL-2.1-or-later", "url": "$FRIBIDI_URL", "sha256": "$FRIBIDI_SHA256"},
    {"name": "harfbuzz", "version": "$HARFBUZZ_VERSION", "license": "MIT", "url": "$HARFBUZZ_URL", "sha256": "$HARFBUZZ_SHA256"},
    {"name": "libunibreak", "version": "$UNIBREAK_VERSION", "license": "Zlib", "url": "$UNIBREAK_URL", "sha256": "$UNIBREAK_SHA256"},
    {"name": "expat", "version": "$EXPAT_VERSION", "license": "MIT", "url": "$EXPAT_URL", "sha256": "$EXPAT_SHA256"},
    {"name": "fontconfig", "version": "$FONTCONFIG_VERSION", "license": "HPND", "url": "$FONTCONFIG_URL", "sha256": "$FONTCONFIG_SHA256"},
    {"name": "nv-codec-headers", "version": "$NVHEADERS_VERSION", "license": "MIT", "url": "$NVHEADERS_URL", "sha256": "$NVHEADERS_SHA256"},
    {"name": "libvpl", "version": "$LIBVPL_VERSION", "license": "MIT", "url": "$LIBVPL_URL", "sha256": "$LIBVPL_SHA256"},
    {"name": "amf-headers", "version": "$AMF_VERSION", "license": "MIT", "url": "$AMF_URL", "sha256": "$AMF_SHA256"},
    {"name": "libva", "version": "$LIBVA_VERSION", "license": "MIT", "url": "$LIBVA_URL", "sha256": "$LIBVA_SHA256"},
    {"name": "zlib", "version": "$ZLIB_VERSION", "license": "Zlib", "url": "$ZLIB_URL", "sha256": "$ZLIB_SHA256"}
  ]
}
EOF
  say "wrote $out"
}

# component_tarball_relpath/component_raw_version: the exact dest filename
# fetch_all_sources() downloads each component to (relative to $DL), and the
# exact raw pin-version string ffmpeg_components.json also uses for that
# component. Single source of truth collect_licenses() reads instead of
# globbing $DL - a build_*() wrapper's own generic fetch (autotools_build /
# cmake_build / meson_build, all three of which name their download from
# the pinned URL's own basename, e.g. "v2.17.0.tar.gz" for libvpl) can
# re-download the SAME tarball under a DIFFERENT name whenever the
# dependency cache is cold, and globbing used to pick up both copies -
# exactly how collect_licenses() used to produce folders named
# "release-3.0.6" / "v2.17.0" instead of the component that owns them.
# Keep these two functions' cases in sync with fetch_all_sources() above.
component_tarball_relpath() { # name
  case "$1" in
    zlib)             echo "zlib-${ZLIB_VERSION}.tar.gz" ;;
    nv-codec-headers) echo "nv-codec-headers-${NVHEADERS_VERSION}.tar.gz" ;;
    libvpl)           echo "libvpl-${LIBVPL_VERSION}.tar.gz" ;;
    amf-headers)      echo "AMF-headers-${AMF_VERSION}.tar.gz" ;;
    libva)            echo "libva-${LIBVA_VERSION}.tar.bz2" ;;
    dav1d)            echo "dav1d-${DAV1D_VERSION}.tar.xz" ;;
    libaom)           echo "libaom-${AOM_VERSION}.tar.gz" ;;
    svt-av1)          echo "SVT-AV1-${SVTAV1_TAG}.tar.gz" ;;
    libvpx)           echo "libvpx-${VPX_VERSION}.tar.gz" ;;
    kvazaar)          echo "kvazaar-${KVAZAAR_VERSION}.tar.gz" ;;
    openh264)         echo "openh264-${OPENH264_TAG}.tar.gz" ;;
    libopus)          echo "opus-${OPUS_VERSION}.tar.gz" ;;
    zimg)             echo "zimg-${ZIMG_VERSION}.tar.gz" ;;
    libwebp)          echo "libwebp-${WEBP_VERSION}.tar.gz" ;;
    freetype)         echo "freetype-${FREETYPE_VERSION}.tar.xz" ;;
    fribidi)          echo "fribidi-${FRIBIDI_VERSION}.tar.xz" ;;
    harfbuzz)         echo "harfbuzz-${HARFBUZZ_VERSION}.tar.xz" ;;
    libunibreak)      echo "libunibreak-${UNIBREAK_VERSION}.tar.gz" ;;
    expat)            echo "expat-${EXPAT_VERSION}.tar.xz" ;;
    fontconfig)       echo "fontconfig-${FONTCONFIG_VERSION}.tar.xz" ;;
    libass)           echo "libass-${LIBASS_VERSION}.tar.gz" ;;
    x264)             echo "x264-${X264_REF}.tar.gz" ;;
    x265)             echo "x265-${X265_VERSION}.tar.gz" ;;
    ffmpeg)           echo "ffmpeg-${FFMPEG_VERSION}.tar.xz" ;;
    *) die "component_tarball_relpath: unknown component '$1'" ;;
  esac
}
component_raw_version() { # name
  case "$1" in
    zlib)             echo "$ZLIB_VERSION" ;;
    nv-codec-headers) echo "$NVHEADERS_VERSION" ;;
    libvpl)           echo "$LIBVPL_VERSION" ;;
    amf-headers)      echo "$AMF_VERSION" ;;
    libva)            echo "$LIBVA_VERSION" ;;
    dav1d)            echo "$DAV1D_VERSION" ;;
    libaom)           echo "$AOM_VERSION" ;;
    svt-av1)          echo "$SVTAV1_TAG" ;;
    libvpx)           echo "$VPX_VERSION" ;;
    kvazaar)          echo "$KVAZAAR_VERSION" ;;
    openh264)         echo "$OPENH264_TAG" ;;
    libopus)          echo "$OPUS_VERSION" ;;
    zimg)             echo "$ZIMG_VERSION" ;;
    libwebp)          echo "$WEBP_VERSION" ;;
    freetype)         echo "$FREETYPE_VERSION" ;;
    fribidi)          echo "$FRIBIDI_VERSION" ;;
    harfbuzz)         echo "$HARFBUZZ_VERSION" ;;
    libunibreak)      echo "$UNIBREAK_VERSION" ;;
    expat)            echo "$EXPAT_VERSION" ;;
    fontconfig)       echo "$FONTCONFIG_VERSION" ;;
    libass)           echo "$LIBASS_VERSION" ;;
    x264)             echo "$X264_REF" ;;
    x265)             echo "$X265_VERSION" ;;
    ffmpeg)           echo "$FFMPEG_VERSION" ;;
    *) die "component_raw_version: unknown component '$1'" ;;
  esac
}

# Folder-display version only - the raw pin string above (used for
# fetching, BUILDINFO.txt and ffmpeg_components.json) is untouched. Strips
# the "release-" prefix (zimg) and a leading "v" before a digit (libvpl,
# libwebp, libvpx, openh264/svt-av1's tag) so folder names read
# "zimg-3.0.6" / "libvpl-2.17.0" instead of the git tag's own spelling.
# nv-codec-headers' "n13.1.15.0" and x264's full commit sha intentionally
# pass through unchanged - neither starts with "v" or "release-".
clean_component_version() { # raw
  local v="$1"
  v="${v#release-}"
  case "$v" in
    v[0-9]*) v="${v#v}" ;;
  esac
  echo "$v"
}

# Every component's own licence file (COPYING, LICENSE, PATENTS, NOTICE,
# FreeType's FTL text), taken from the pinned archives into OUTDIR/licenses/
# so they travel with the binaries: MIT and BSD require the text with a
# binary distribution, not only in the source bundle. Folders are named
# "<component>-<version>" (e.g. "zimg-3.0.6", "libvpl-2.17.0") straight from
# ffmpeg_components.json's own name+version, driven by an explicit,
# target-filtered component list - never by globbing $DL (see
# component_tarball_relpath's comment for why) - so every component gets
# exactly one folder and every folder maps to exactly one component, or the
# build fails.
collect_licenses() {
  local lic="$OUTDIR/licenses"
  rm -rf "$lic"
  mkdir -p "$lic"

  # Mirrors fetch_all_sources()'s own conditionals exactly: amf-headers only
  # on the mingw (Windows) target, libva/expat/fontconfig only on native
  # Linux, x264/x265 only in the gpl variant. COMMON_COMPONENT_NAMES lists
  # every name either branch could need; this is where the target split
  # actually happens.
  local -a applicable=(zlib nv-codec-headers libvpl)
  if [ "$MINGW" = "1" ]; then
    applicable+=(amf-headers)
  else
    applicable+=(libva)
  fi
  applicable+=(dav1d libaom svt-av1 libvpx kvazaar openh264 libopus zimg libwebp freetype fribidi harfbuzz libunibreak)
  if [ "$MINGW" != "1" ]; then
    applicable+=(expat fontconfig)
  fi
  applicable+=(libass)
  if [ "$VARIANT" = "gpl" ]; then
    applicable+=(x264 x265)
  fi
  applicable+=(ffmpeg)

  local name relpath rawver cleanver folder tgz members
  local -a expected_folders=()
  for name in "${applicable[@]}"; do
    grep -q "\"name\": \"$name\"" "$REPO_ROOT/scripts/release/ffmpeg_components.json" \
      || die "collect_licenses: component '$name' not found in ffmpeg_components.json - names have drifted"

    relpath="$(component_tarball_relpath "$name")"
    rawver="$(component_raw_version "$name")"
    cleanver="$(clean_component_version "$rawver")"
    folder="$name-$cleanver"
    expected_folders+=("$folder")
    tgz="$DL/$relpath"
    [ -f "$tgz" ] || die "collect_licenses: expected tarball for '$name' missing at $tgz (fetch_all_sources should have fetched it)"

    mkdir -p "$lic/$folder"
    members="$(tar -tf "$tgz" 2>/dev/null \
      | grep -E '^[^/]+/((COPYING|LICENSE|LICENCE|COPYRIGHT|NOTICE|PATENTS)[^/]*|docs/FTL\.TXT)$' || true)"
    if [ -n "$members" ]; then
      # shellcheck disable=SC2086 # one archive member per word, none with spaces
      tar -xf "$tgz" -C "$lic/$folder" --strip-components=1 $members
    fi

    if [ -z "$(ls -A "$lic/$folder" 2>/dev/null)" ]; then
      case "$name" in
        nv-codec-headers)
          # Headers-only release - no COPYING/LICENSE member in the tarball
          # (checked by hand). The MIT text is in every header's own
          # leading comment instead (identical wording in all 5, confirmed
          # by hand); nvEncodeAPI.h's copy names NVIDIA explicitly, so use
          # it. Extracted straight from the already-downloaded,
          # already-sha256-verified tarball - nothing new to trust.
          # Extract to a file rather than piping straight into awk: awk's
          # early `exit` once it hits the closing `*/` would otherwise
          # SIGPIPE the still-writing `tar -O`, which `pipefail` reports as
          # a pipeline failure (the same class of trap this script's own
          # ffmpeg_configure()/the smoke-test workflow already comment on).
          local nvheader="$WORK/nvEncodeAPI.h"
          tar -xzOf "$tgz" "nv-codec-headers-$rawver/include/ffnvcodec/nvEncodeAPI.h" > "$nvheader" \
            || die "collect_licenses: could not extract nv-codec-headers' nvEncodeAPI.h"
          awk '/^\/\*/{p=1} p{print} p&&/\*\//{exit}' "$nvheader" > "$lic/$folder/LICENSE"
          [ -s "$lic/$folder/LICENSE" ] \
            || die "collect_licenses: nv-codec-headers LICENSE extraction produced nothing"
          ;;
        amf-headers)
          # Same story - the headers-only release asset has no LICENSE
          # member either. AMD's MIT text lives in the main AMF repo's
          # LICENSE.txt at the same tag; AMF_LICENSE_URL/SHA256 above pin
          # and verify it like every other download in this script.
          fetch_pinned "$AMF_LICENSE_URL" "$AMF_LICENSE_SHA256" "$DL/AMF-LICENSE-${rawver}.txt"
          cp "$DL/AMF-LICENSE-${rawver}.txt" "$lic/$folder/LICENSE.txt"
          ;;
        *)
          die "collect_licenses: component '$name' ($tgz) has no recognizable licence file and no synthesis rule - add one"
          ;;
      esac
    fi
  done

  # Belt-and-braces: every folder created above maps to exactly one
  # component and every applicable component got exactly one folder. Since
  # the loop above builds $lic entirely from the explicit $applicable list
  # (never from a glob), the only way this can fail is a bug in the mapping
  # itself - which is exactly what should fail the build instead of
  # shipping silently.
  local expected actual
  expected="$(printf '%s\n' "${expected_folders[@]}" | sort)"
  actual="$(ls -1 "$lic" | sort)"
  [ "$expected" = "$actual" ] \
    || die "collect_licenses: folder set mismatch - expected:
$expected
got:
$actual"
}

# ---------------------------------------------------------------------------
# main
# ---------------------------------------------------------------------------

main() {
  install_deps
  write_components_json
  # Every pinned tarball, sha256-verified, regardless of cache status below -
  # the Corresponding Source bundle must be complete even when the compiled
  # PREFIX comes straight from cache and build_all() never runs.
  fetch_all_sources

  mkdir -p "$CACHE_ROOT"
  exec 9>"$CACHE_ROOT/.lock"
  flock 9
  if [ -f "$CACHE_ENTRY/.complete" ] && [ -f "$PREFIX/bin/ffmpeg${EXE_SUFFIX}" ]; then
    say "reusing cached build $CACHE_KEY"
  else
    say "no cached build for $CACHE_KEY - building FFmpeg $FFMPEG_VERSION from source ($TARGET, $VARIANT)"
    rm -rf "$CACHE_ENTRY"
    mkdir -p "$PREFIX"
    local started=$SECONDS
    build_all
    touch "$CACHE_ENTRY/.complete"
    say "built in $(( (SECONDS - started) / 60 )) min $(( (SECONDS - started) % 60 )) s"
    # Keep the 4 most recent (target,variant) cache slots combined across
    # however many of the 4 combinations have been built on this runner;
    # a pin bump should not fill the runner's disk indefinitely.
    ls -1dt "$CACHE_ROOT"/*/ 2>/dev/null | tail -n +9 | xargs -r rm -rf
  fi

  [ -f "$PREFIX/bin/ffmpeg${EXE_SUFFIX}" ] || die "no ffmpeg${EXE_SUFFIX} in $PREFIX/bin after build"
  [ -f "$PREFIX/bin/ffprobe${EXE_SUFFIX}" ] || die "no ffprobe${EXE_SUFFIX} in $PREFIX/bin after build"

  mkdir -p "$OUTDIR" "$OUTDIR/source"
  cp "$PREFIX/bin/ffmpeg${EXE_SUFFIX}" "$OUTDIR/ffmpeg${EXE_SUFFIX}"
  cp "$PREFIX/bin/ffprobe${EXE_SUFFIX}" "$OUTDIR/ffprobe${EXE_SUFFIX}"
  chmod 755 "$OUTDIR/ffmpeg${EXE_SUFFIX}" "$OUTDIR/ffprobe${EXE_SUFFIX}"
  collect_licenses

  {
    echo "Grand Media Station - FFmpeg program build ($TARGET, $VARIANT variant)"
    echo "recipe: $RECIPE_ID (first 16 hex digits of the sha256 of build_ffmpeg_program.sh)"
    echo "built on: $(uname -a)"
    echo
    echo "FFmpeg $FFMPEG_VERSION  $FFMPEG_URL"
    echo "  sha256 $FFMPEG_SHA256, signed by $FFMPEG_KEY_FPR"
    echo
    if [ "$TARGET" = "linux-x64" ]; then
      echo "--- ffmpeg -version ---"
      "$OUTDIR/ffmpeg" -version 2>&1 || true
      echo
      echo "--- ffmpeg -buildconf ---"
      "$OUTDIR/ffmpeg" -buildconf 2>&1 || true
    elif command -v wine >/dev/null 2>&1; then
      echo "--- ffmpeg -version (via wine) ---"
      wine "$OUTDIR/ffmpeg.exe" -version 2>&1 || true
      echo
      echo "--- ffmpeg -buildconf (via wine) ---"
      wine "$OUTDIR/ffmpeg.exe" -buildconf 2>&1 || true
    else
      echo "(cross-compiled for Windows on this Linux build host; wine not"
      echo " present, so -buildconf was not captured here - see the smoke-test"
      echo " step in .github/workflows/ffmpeg-program.yml for a runtime check.)"
    fi
    echo
    echo "Every pinned component (name, version, sha256): see"
    echo "scripts/release/ffmpeg_components.json alongside this script, and"
    echo "source/ next to this file for the tarballs themselves."
  } > "$OUTDIR/BUILDINFO.txt"
  cp "$OUTDIR/BUILDINFO.txt" "$OUTDIR/source/BUILDINFO.txt"

  # Corresponding Source: every tarball this (target,variant) needs - DL
  # always holds them by this point (fetch_all_sources ran above
  # unconditionally, cache hit or not) - plus this script itself.
  cp "$DL"/*.tar.* "$OUTDIR/source/" 2>/dev/null || true
  cp "$SCRIPT_PATH" "$OUTDIR/source/build_ffmpeg_program.sh"

  say "done - $OUTDIR/ffmpeg${EXE_SUFFIX}, $OUTDIR/ffprobe${EXE_SUFFIX}, $(find "$OUTDIR/source" -type f | wc -l) source file(s)"
}

main "$@"
