#!/bin/zsh
# Builds the ffmpeg that ships inside Convert (owner decision 2026-11-13, replacing D1): ffmpeg and ffprobe for
# Apple silicon, LGPL only (no --enable-gpl, no --enable-nonfree, no x264, x265, fdk-aac or xvid), with VideoToolbox
# for H.264 and HEVC and these BSD or LGPL libraries linked in statically:
#   libvpx (VP8, VP9)  libopus  libvorbis + libogg  libmp3lame  libtheora  libdav1d and SVT-AV1 (AV1)
#   snappy (HAP)  libwebp
# ffmpeg's own libraries are built as dylibs (Contents/Frameworks) and the 2 programs link them through @rpath
# (Contents/Helpers), so anyone can swap in their own build of the same libraries, as the LGPL asks.
# Every source is a pinned release with its SHA-256 below; a mismatch stops the build. Network protocols are off:
# the bundled ffmpeg can only read and write files.
#   tools/convert/build-ffmpeg.sh      (sources and the build live in ~/Library/Caches/Toolbox, never in iCloud)
# Output: Apps/Convert/Vendor/ffmpeg/{Helpers,Frameworks,CONFIGURE.txt,SOURCES.txt,licenses/}
set -euo pipefail
cd "${0:A:h}/../.."
REPO=$PWD
CACHE="$HOME/Library/Caches/Toolbox"
DL="$CACHE/ffmpeg-src/dl"
# The build itself runs under a neutral folder: build paths end up inside the binaries (ffmpeg's configuration line,
# file names in asserts), and they must never carry a home folder or a user name.
WORK=/private/tmp/handful-ffmpeg
SRC="$WORK/src"
PREFIX="$WORK/prefix"
FF="$WORK/ffmpeg"
TOOLS="$CACHE/ffmpeg-tools"          # a Python venv with meson, ninja, cmake and pkgconf (nothing from Homebrew)
DEST="$REPO/Apps/Convert/Vendor/ffmpeg"

# name | url | sha256
SOURCES=(
  "ffmpeg-9.0.2.tar.xz|https://ffmpeg.org/releases/ffmpeg-9.0.2.tar.xz|8c3850283eb25fa026482078a04051e0be17347b09ef81a0849bec15a96e002e"
  "libvpx-1.17.0.tar.gz|https://github.com/webmproject/libvpx/archive/refs/tags/v1.17.0.tar.gz|1020f184046187baa2985dbde38e0691f49c44088bca7a1842b0236c6081dc0a"
  "dav1d-1.5.4.tar.xz|https://downloads.videolan.org/pub/videolan/dav1d/1.5.4/dav1d-1.5.4.tar.xz|686616b7c69eb88d44459391ab25cac13b6647a3b288835c5784e71c1514a5c5"
  "SVT-AV1-v4.3.0.tar.gz|https://gitlab.com/AOMediaCodec/SVT-AV1/-/archive/v4.3.0/SVT-AV1-v4.3.0.tar.gz|95ce8fc2381ba707e65ac8b9b2e165915bfbe9cd4d2f7b0f58d64ce31bd98f6d"
  "opus-1.6.1.tar.gz|https://downloads.xiph.org/releases/opus/opus-1.6.1.tar.gz|6ffcb593207be92584df15b32466ed64bbec99109f007c82205f0194572411a1"
  "libogg-1.3.6.tar.xz|https://downloads.xiph.org/releases/ogg/libogg-1.3.6.tar.xz|5c8253428e181840cd20d41f3ca16557a9cc04bad4a3d04cce84808677fa1061"
  "libvorbis-1.3.7.tar.xz|https://downloads.xiph.org/releases/vorbis/libvorbis-1.3.7.tar.xz|b33cc4934322bcbf6efcbacf49e3ca01aadbea4114ec9589d1b1e9d20f72954b"
  "libtheora-1.2.0.tar.xz|https://downloads.xiph.org/releases/theora/libtheora-1.2.0.tar.xz|ebdf77a8f5c0a8f7a9e42323844fa09502b34eb1d1fece7b5f54da41fe2122ec"
  "lame-3.100.tar.gz|https://downloads.sourceforge.net/project/lame/lame/3.100/lame-3.100.tar.gz|ddfe36cab873794038ae2c1210557ad34857a4b6bdc515785d1da9e175b1da1e"
  "snappy-1.2.2.tar.gz|https://github.com/google/snappy/archive/refs/tags/1.2.2.tar.gz|90f74bc1fbf78a6c56b3c4a082a05103b3a56bb17bca1a27e052ea11723292dc"
  "libwebp-1.5.0.tar.gz|https://storage.googleapis.com/downloads.webmproject.org/releases/webp/libwebp-1.5.0.tar.gz|7d6fab70cf844bf6769077bd5d7a74893f8ffd4dfb42861745750c63c2a5c92c"
)

step() { print -P "%B==> $1%b" }

step "Build tools"
[[ -x "$TOOLS/bin/meson" && -x "$TOOLS/bin/cmake" && -x "$TOOLS/bin/pkgconf" ]] || {
  /usr/bin/python3 -m venv "$TOOLS" && "$TOOLS/bin/pip" install -q meson ninja cmake pkgconf; }

step "Sources (pinned, SHA-256 checked)"
mkdir -p "$DL"
rm -rf "$SRC" && mkdir -p "$SRC"
for s in $SOURCES; do
  name=${s%%|*}; rest=${s#*|}; url=${rest%%|*}; sum=${rest#*|}
  [[ -s "$DL/$name" ]] || curl -fsSL -o "$DL/$name" "$url"
  got=$(shasum -a 256 "$DL/$name" | awk '{print $1}')
  [[ "$got" == "$sum" ]] || { print "checksum mismatch for $name: $got"; exit 1 }
  tar -xf "$DL/$name" -C "$SRC"
done

# A clean environment: Apple's clang and SDK, the venv's tools, and nothing from /opt/homebrew or /usr/local.
export SDKROOT="$(xcrun --show-sdk-path)"
export PATH="$TOOLS/bin:/usr/bin:/bin:/usr/sbin:/sbin"
export MACOSX_DEPLOYMENT_TARGET=26.0
export CC="$(xcrun -f clang)" CXX="$(xcrun -f clang++)"
export CFLAGS="-arch arm64 -mmacosx-version-min=26.0 -O2 -fPIC -isysroot $SDKROOT -ffile-prefix-map=$WORK/=/"
export CXXFLAGS="$CFLAGS" LDFLAGS="-arch arm64 -mmacosx-version-min=26.0 -isysroot $SDKROOT"
export PKG_CONFIG="$TOOLS/bin/pkgconf" PKG_CONFIG_LIBDIR="$PREFIX/lib/pkgconfig" PKG_CONFIG_PATH=""
rm -rf "$PREFIX" "$FF" && mkdir -p "$PREFIX" "$FF"
J=$(sysctl -n hw.ncpu)
LOG="$WORK/logs"; mkdir -p "$LOG"
quiet() { local n=$1; shift; "$@" >"$LOG/$n.log" 2>&1 || { print "failed: $n (see $LOG/$n.log)"; tail -20 "$LOG/$n.log"; exit 1 } }
autotools() {   # dir, name, extra configure args
  local d=$1 n=$2; shift 2
  (cd "$SRC/$d" && quiet "$n-configure" ./configure --prefix="$PREFIX" --disable-shared --enable-static "$@" \
     && quiet "$n-make" make -j$J && quiet "$n-install" make install)
}
cmakebuild() {  # dir, name, extra cmake args
  local d=$1 n=$2; shift 2
  quiet "$n-configure" cmake -S "$SRC/$d" -B "$SRC/$d/_build" -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX="$PREFIX" \
    -DCMAKE_INSTALL_LIBDIR=lib -DCMAKE_OSX_ARCHITECTURES=arm64 -DCMAKE_OSX_DEPLOYMENT_TARGET=26.0 -DCMAKE_OSX_SYSROOT="$SDKROOT" \
    -DCMAKE_POSITION_INDEPENDENT_CODE=ON -DBUILD_SHARED_LIBS=OFF -DCMAKE_FIND_FRAMEWORK=NEVER -DCMAKE_IGNORE_PREFIX_PATH="/opt/homebrew;/usr/local" "$@"
  quiet "$n-build" cmake --build "$SRC/$d/_build" --parallel $J
  quiet "$n-install" cmake --install "$SRC/$d/_build"
}

step "libogg";    autotools libogg-1.3.6 ogg
step "libvorbis"
sed -i '' 's/-force_cpusubtype_ALL//g' "$SRC/libvorbis-1.3.7/configure"   # an old PowerPC flag Apple's arm64 linker refuses
autotools libvorbis-1.3.7 vorbis --with-ogg="$PREFIX" --disable-oggtest --disable-docs --disable-examples
step "libopus";   autotools opus-1.6.1 opus --disable-doc --disable-extra-programs
step "libtheora"; autotools libtheora-1.2.0 theora --with-ogg="$PREFIX" --disable-oggtest --disable-vorbistest --disable-examples --disable-spec --disable-doc
step "libmp3lame"; autotools lame-3.100 lame --disable-frontend --disable-decoder --disable-gtktest --enable-nasm=no
step "libvpx"
(cd "$SRC/libvpx-1.17.0" && quiet vpx-configure ./configure --prefix="$PREFIX" --target=arm64-darwin25-gcc --enable-pic --disable-shared --enable-static \
   --enable-vp8 --enable-vp9 --enable-vp9-highbitdepth --disable-examples --disable-tools --disable-docs --disable-unit-tests \
   --extra-cflags="-mmacosx-version-min=26.0" && quiet vpx-make make -j$J && quiet vpx-install make install)
step "dav1d"
quiet dav1d-setup meson setup "$SRC/dav1d-1.5.4/_build" "$SRC/dav1d-1.5.4" --prefix="$PREFIX" --libdir=lib --buildtype=release \
  --default-library=static -Denable_tools=false -Denable_tests=false -Denable_examples=false
quiet dav1d-build ninja -C "$SRC/dav1d-1.5.4/_build"
quiet dav1d-install ninja -C "$SRC/dav1d-1.5.4/_build" install
step "SVT-AV1"; cmakebuild SVT-AV1-v4.3.0 svtav1 -DBUILD_APPS=OFF -DBUILD_TESTING=OFF -DENABLE_NASM=OFF
step "snappy";  cmakebuild snappy-1.2.2 snappy -DSNAPPY_BUILD_TESTS=OFF -DSNAPPY_BUILD_BENCHMARKS=OFF
step "libwebp"; cmakebuild libwebp-1.5.0 webp -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_WEBPMUX=OFF \
  -DWEBP_BUILD_EXTRAS=OFF -DWEBP_USE_THREAD=ON

# ffmpeg's configure links snappy with -lstdc++, which macOS no longer has; an empty stand-in lets that line pass and
# --extra-libs adds Apple's libc++ instead. ffmpeg's own sources are not changed.
mkdir -p "$PREFIX/stub"
print 'void tb_stub(void) {}' > "$PREFIX/stub/stub.c"
"$CC" $=CFLAGS -c "$PREFIX/stub/stub.c" -o "$PREFIX/stub/stub.o" && ar rcs "$PREFIX/stub/libstdc++.a" "$PREFIX/stub/stub.o"

step "ffmpeg (LGPL)"
CONFIGURE=(--prefix="$FF" --arch=arm64 --target-os=darwin --cc=clang --cxx=clang++
  --enable-shared --disable-static --install-name-dir=@rpath
  --disable-gpl --disable-nonfree --disable-autodetect --disable-network --disable-doc --disable-ffplay --disable-debug
  --enable-pthreads --enable-videotoolbox --enable-audiotoolbox --enable-zlib --enable-bzlib --enable-iconv
  --enable-libvpx --enable-libopus --enable-libvorbis --enable-libmp3lame --enable-libtheora --enable-libdav1d
  --enable-libsvtav1 --enable-libsnappy --enable-libwebp
  --pkg-config-flags=--static
  --extra-cflags="-mmacosx-version-min=26.0 -I$PREFIX/include" --extra-ldflags="-mmacosx-version-min=26.0 -L$PREFIX/lib -L$PREFIX/stub"
  "--extra-libs=-lc++ -liconv" --extra-ldexeflags=-Wl,-rpath,@executable_path/../Frameworks)
(cd "$SRC/ffmpeg-9.0.2" && quiet ffmpeg-configure ./configure $CONFIGURE && quiet ffmpeg-make make -j$J && quiet ffmpeg-install make install)

step "Into $DEST"
rm -rf "$DEST" && mkdir -p "$DEST/Helpers" "$DEST/Frameworks" "$DEST/licenses"
for p in ffmpeg ffprobe; do cp "$FF/bin/$p" "$DEST/Helpers/$p"; done
for lib in "$FF"/lib/lib*.dylib(.); do   # the real files; each is named by the install name the programs ask for
  id=$(otool -D "$lib" | tail -1); cp "$lib" "$DEST/Frameworks/${id:t}"
done
chmod 755 "$DEST"/Helpers/* && chmod 644 "$DEST"/Frameworks/*
strip -x "$DEST"/Helpers/* "$DEST"/Frameworks/*
# Only ffmpeg's own dylibs (by @rpath) and macOS itself may be linked.
for f in "$DEST"/Helpers/* "$DEST"/Frameworks/*; do
  bad=$(otool -L "$f" | tail -n +2 | awk '{print $1}' | grep -vE '^(@rpath/lib(av|sw)[a-z]*\.[0-9]+\.dylib|/usr/lib/|/System/Library/)' || true)
  [[ -z "$bad" ]] || { print "$f links outside the app and macOS: $bad"; exit 1 }
done
"$DEST/Helpers/ffmpeg" -hide_banner -L 2>/dev/null | grep -q "GNU Lesser General Public" || { print "the build is not LGPL"; exit 1 }
if "$DEST/Helpers/ffmpeg" -hide_banner -buildconf | grep -qE -- "--enable-(gpl|nonfree|version3)"; then print "a GPL, nonfree or version 3 option is on"; exit 1; fi
for f in "$DEST"/Helpers/* "$DEST"/Frameworks/*; do
  if strings -a "$f" | grep -qF -e "$HOME" -e "/Users/"; then print "$f names a home folder"; exit 1; fi
done
print -r -- "./configure $("$DEST/Helpers/ffmpeg" -hide_banner -version | sed -n 's/^configuration: //p')" > "$DEST/CONFIGURE.txt"
{ print "Sources of the bundled ffmpeg (tools/convert/build-ffmpeg.sh), SHA-256:"; for s in $SOURCES; do n=${s%%|*}; r=${s#*|}; print "${r#*|}  $n  ${r%%|*}"; done; } > "$DEST/SOURCES.txt"
cp "$SRC/ffmpeg-9.0.2/COPYING.LGPLv2.1" "$DEST/licenses/ffmpeg-COPYING.LGPLv2.1"
cp "$SRC/ffmpeg-9.0.2/LICENSE.md" "$DEST/licenses/ffmpeg-LICENSE.md"
cp "$SRC/libvpx-1.17.0/LICENSE" "$DEST/licenses/libvpx-LICENSE"; cp "$SRC/libvpx-1.17.0/PATENTS" "$DEST/licenses/libvpx-PATENTS"
cp "$SRC/opus-1.6.1/COPYING" "$DEST/licenses/opus-COPYING"
cp "$SRC/libogg-1.3.6/COPYING" "$DEST/licenses/libogg-COPYING"
cp "$SRC/libvorbis-1.3.7/COPYING" "$DEST/licenses/libvorbis-COPYING"
cp "$SRC/libtheora-1.2.0/COPYING" "$DEST/licenses/libtheora-COPYING"
cp "$SRC/lame-3.100/COPYING" "$DEST/licenses/lame-COPYING"
cp "$SRC/dav1d-1.5.4/COPYING" "$DEST/licenses/dav1d-COPYING"
cp "$SRC/SVT-AV1-v4.3.0/LICENSE.md" "$DEST/licenses/SVT-AV1-LICENSE.md"; cp "$SRC/SVT-AV1-v4.3.0/PATENTS.md" "$DEST/licenses/SVT-AV1-PATENTS.md"
cp "$SRC/snappy-1.2.2/COPYING" "$DEST/licenses/snappy-COPYING"
cp "$SRC/libwebp-1.5.0/COPYING" "$DEST/licenses/libwebp-COPYING"
"$DEST/Helpers/ffmpeg" -hide_banner -version | head -1
du -sh "$DEST"
