#!/bin/bash
# Builds the ffmpeg the Mac App Store edition bundles: FFmpeg's own code only, under the LGPL (no --enable-gpl, no
# --enable-nonfree, no outside codec library), arm64, macOS 14 or later, linked only against macOS's own libraries.
#
#   build_lgpl_ffmpeg.sh <ffmpeg-X.Y.Z.tar.xz> <work folder WITHOUT spaces in its path> <output file>
#
# FFmpeg's configure refuses a source path with spaces, and this project's disk has one in its name, so the work
# folder must be elsewhere. The tools come from macOS only (PATH below): nothing of Homebrew is found or linked.
set -euo pipefail
TARBALL="$1"; WORK="$2"; OUT="$3"
case "$WORK" in *" "*) echo "the work folder's path must not contain spaces" >&2; exit 2;; esac
export PATH=/usr/bin:/bin:/usr/sbin:/sbin
export MACOSX_DEPLOYMENT_TARGET=14.0
rm -rf "$WORK"; mkdir -p "$WORK/src"
/usr/bin/tar -xf "$TARBALL" -C "$WORK/src" --strip-components 1
cd "$WORK/src"
CONFIGURE_FLAGS=(
  --prefix=/usr/local --arch=arm64 --cc=/usr/bin/clang   # (never installed: the prefix only appears in the
                                                        # binary's own "configuration" line, so no local path does)
  --disable-autodetect                # nothing found on this Mac by chance is linked in
  --enable-securetransport            # https through macOS's own TLS
  --enable-zlib --enable-videotoolbox --enable-audiotoolbox
  --disable-indevs --disable-outdevs  # no camera, microphone or screen capture code in the binary ...
  --enable-indev=lavfi                # ... only the filter-graph input the project's tests make their media with
  --disable-ffplay --disable-ffprobe --disable-doc --disable-debug
  --disable-shared --enable-static --enable-runtime-cpudetect --enable-neon
  --extra-cflags=-mmacosx-version-min=14.0 --extra-ldflags=-mmacosx-version-min=14.0
)
./configure "${CONFIGURE_FLAGS[@]}"
/usr/bin/make -j"$(/usr/sbin/sysctl -n hw.ncpu)"
mkdir -p "$(dirname "$OUT")"
cp "$WORK/src/ffmpeg" "$OUT"
/usr/bin/strip -x "$OUT"
echo "built: $OUT"
