#!/bin/bash
# ffmpeg and ffprobe for Astrape Companion: universal (arm64 + x86_64), macOS 14, LGPL-2.1-or-later.
# The app ships the two programs in Contents/Helpers and FFmpeg's libraries, shared by both, in Contents/Frameworks
# (project.yml), and uses them before any other ffmpeg (FFmpegTools.locate). Shared, not static: one copy of the
# decoders instead of two (static, each universal program was 45 MB), and the libraries can be replaced (LGPL).
#
#   Scripts/companion-ffmpeg/build.sh      → build/companion-ffmpeg/universal/{bin,lib,LICENSES}
#
# The sources are the tarballs Astrape for Apple TV uses, which astrape.app/ffmpeg/ publishes (the LGPL source offer):
# FFmpeg 7.1 and dav1d 1.5.1, checked against their SHA-256. Taken from ~/gitea/astrape-website/public/ffmpeg when
# there, else downloaded from ffmpeg.org and videolan.org. This script is published next to them.
#
# What is in it, and why (the companion's ffmpeg command lines are in AstrapeCompanion/Core/Transcode, Media, Stream):
#   - every demuxer, decoder, parser, protocol, bitstream filter and filter FFmpeg has without outside libraries:
#     it reads whatever the user shares (local files, http/https, HLS); https through macOS's Secure Transport
#   - dav1d (BSD) for AV1 on Macs without an AV1 decoder in hardware; VP9 uses FFmpeg's own decoder
#   - VideoToolbox (hardware HEVC / H.264 encoders, -hwaccel videotoolbox) and AudioToolbox
#   - encoders: hevc_videotoolbox, h264_videotoolbox, aac, eac3, ac3 (eac3's sibling), webvtt (subtitles), mjpeg
#     (thumbnails); muxers: hls, mp4/mov (fMP4 segments), webvtt, image2 (thumbnails), null
#   - no GPL or nonfree parts (--disable-gpl --disable-nonfree are FFmpeg's defaults; checked below), no avdevice
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
OUT="${OUT:-$ROOT/build/companion-ffmpeg}"
SITE_SOURCES="${SITE_SOURCES:-$HOME/gitea/astrape-website/public/ffmpeg}"
MIN_MACOS=14.0
FFMPEG=ffmpeg-7.1      FFMPEG_SHA=fd59e6160476095082e94150ada5a6032d7dcc282fe38ce682a00c18e7820528
DAV1D=dav1d-1.5.1      DAV1D_SHA=401813f1f89fa8fd4295805aa5284d9aed9bc7fc1fdbe554af4292f64cbabe21
JOBS="$(sysctl -n hw.ncpu 2>/dev/null || getconf _NPROCESSORS_ONLN)"

die() { echo "companion-ffmpeg: $*" >&2; exit 1; }
say() { echo "companion-ffmpeg: $*"; }
for t in clang lipo meson ninja nasm pkg-config shasum strip; do command -v "$t" >/dev/null || die "missing tool: $t (brew install meson ninja nasm pkg-config)"; done

mkdir -p "$OUT/src"
fetch() {  # name sha url
  local file="$OUT/src/$1"
  if [[ ! -f "$file" ]]; then
    if [[ -f "$SITE_SOURCES/$1" ]]; then cp "$SITE_SOURCES/$1" "$file"; else curl -fsSL --max-time 300 -o "$file" "$3"; fi
  fi
  [[ "$(shasum -a 256 "$file" | cut -d' ' -f1)" == "$2" ]] || die "$1: SHA-256 doesn't match"
}
fetch "$FFMPEG.tar.bz2" "$FFMPEG_SHA" "https://ffmpeg.org/releases/$FFMPEG.tar.bz2"
fetch "$DAV1D.tar.xz" "$DAV1D_SHA" "https://downloads.videolan.org/pub/videolan/dav1d/${DAV1D#dav1d-}/$DAV1D.tar.xz"

build_arch() {
  local arch="$1" prefix="$OUT/$1" work="$OUT/work-$1"
  rm -rf "$work" "$prefix"; mkdir -p "$work" "$prefix"
  tar -xf "$OUT/src/$FFMPEG.tar.bz2" -C "$work"
  tar -xf "$OUT/src/$DAV1D.tar.xz" -C "$work"
  local cflags="-arch $arch -mmacosx-version-min=$MIN_MACOS"

  say "$arch: dav1d"
  local cpu=aarch64; [[ "$arch" == x86_64 ]] && cpu=x86_64
  cat >"$work/cross.txt" <<EOF
[binaries]
c = 'clang'
ar = 'ar'
strip = 'strip'
[built-in options]
c_args = ['-arch', '$arch', '-mmacosx-version-min=$MIN_MACOS']
c_link_args = ['-arch', '$arch', '-mmacosx-version-min=$MIN_MACOS']
[host_machine]
system = 'darwin'
cpu_family = '$cpu'
cpu = '$cpu'
endian = 'little'
EOF
  (cd "$work/$DAV1D" && meson setup build --cross-file "$work/cross.txt" --prefix "$prefix" --libdir lib \
      --buildtype release --default-library static -Denable_tools=false -Denable_tests=false >"$work/dav1d.log" 2>&1 \
    && ninja -C build install >>"$work/dav1d.log" 2>&1) || { tail -n 20 "$work/dav1d.log" >&2; die "$arch: dav1d failed"; }

  say "$arch: FFmpeg (log: $work/ffmpeg.log)"
  local cross=(); [[ "$arch" != "$(uname -m)" ]] && cross=(--enable-cross-compile)
  (cd "$work/$FFMPEG" && PKG_CONFIG_PATH="$prefix/lib/pkgconfig" PKG_CONFIG_LIBDIR="$prefix/lib/pkgconfig" ./configure \
      --prefix="$prefix" --arch="$arch" --target-os=darwin --cc=clang ${cross[@]+"${cross[@]}"} \
      --extra-cflags="$cflags" --extra-libs=-liconv --pkg-config-flags=--static \
      --extra-ldflags="$cflags -Wl,-rpath,@executable_path/../Frameworks -Wl,-rpath,@executable_path/../lib" \
      --enable-shared --disable-static --install-name-dir=@rpath --disable-doc --disable-debug --disable-ffplay --enable-ffmpeg --enable-ffprobe \
      --disable-autodetect --enable-videotoolbox --enable-audiotoolbox --enable-securetransport \
      --enable-zlib --enable-bzlib --enable-iconv --enable-libdav1d \
      --disable-avdevice --disable-indevs --disable-outdevs \
      --disable-encoders --enable-encoder=hevc_videotoolbox,h264_videotoolbox,aac,eac3,ac3,webvtt,mjpeg \
      --disable-muxers --enable-muxer=hls,mp4,mov,webvtt,image2,mjpeg,null \
      >"$work/ffmpeg.log" 2>&1 \
    && make -j"$JOBS" >>"$work/ffmpeg.log" 2>&1 && make install >>"$work/ffmpeg.log" 2>&1) \
    || { tail -n 30 "$work/ffmpeg.log" >&2; die "$arch: FFmpeg failed"; }
  grep -q "License: LGPL version 2.1 or later" "$work/ffmpeg.log" || die "$arch: configure didn't say LGPL 2.1 or later"
  cp "$work/$FFMPEG/COPYING.LGPLv2.1" "$work/$DAV1D/COPYING" "$prefix/"
}

for arch in arm64 x86_64; do build_arch "$arch"; done

say "universal"
U="$OUT/universal"; rm -rf "$U"; mkdir -p "$U/bin" "$U/lib" "$U/LICENSES"
universal() {  # arm64 file, x86_64 file, output
  lipo -create "$1" "$2" -output "$3"
  strip -x "$3"
  local archs; archs="$(lipo -archs "$3")"
  [[ "$archs" == *arm64* && "$archs" == *x86_64* ]] || die "$3 isn't universal"
}
for tool in ffmpeg ffprobe; do universal "$OUT/arm64/bin/$tool" "$OUT/x86_64/bin/$tool" "$U/bin/$tool"; done
# Each library under the name the programs load it by (@rpath/libavcodec.61.dylib).
for lib in "$OUT"/arm64/lib/lib*.dylib; do
  [[ -L "$lib" ]] && continue
  name="$(basename "$(otool -D "$lib" | tail -n 1)")"
  [[ -f "$U/lib/$name" ]] || universal "$lib" "$OUT/x86_64/lib/$(basename "$lib")" "$U/lib/$name"
done
cp "$OUT/arm64/COPYING.LGPLv2.1" "$U/LICENSES/FFmpeg-COPYING.LGPLv2.1"
cp "$OUT/arm64/COPYING" "$U/LICENSES/dav1d-COPYING"
cat >"$U/LICENSES/README.txt" <<EOF
Astrape Companion includes ffmpeg, ffprobe and the FFmpeg libraries (Contents/Frameworks/libav*.dylib,
libsw*.dylib) from FFmpeg 7.1 (https://ffmpeg.org), licensed under the
GNU Lesser General Public License, version 2.1 or later (FFmpeg-COPYING.LGPLv2.1), built with dav1d 1.5.1
(https://code.videolan.org/videolan/dav1d), licensed under the BSD 2-Clause license (dav1d-COPYING).
No GPL or nonfree components are included.

The source code of both, and the script that builds these programs, are at https://astrape.app/ffmpeg/
EOF

# The programs load only our libraries and the system's, have the encoders the companion asks for, and nothing GPL.
for f in "$U"/bin/* "$U"/lib/*; do
  outside="$(otool -L "$f" | grep -E $'^\t' | grep -v -E "@rpath/lib(av|sw)|/usr/lib/|/System/Library/" || true)"
  [[ -z "$outside" ]] || die "$(basename "$f") links something outside FFmpeg and the system: $outside"
done
encoders="$("$U/bin/ffmpeg" -hide_banner -encoders 2>/dev/null)"; decoders="$("$U/bin/ffmpeg" -hide_banner -decoders 2>/dev/null)"
buildconf="$("$U/bin/ffmpeg" -hide_banner -buildconf 2>/dev/null)"
[[ "$encoders" == *hevc_videotoolbox* && "$encoders" == *h264_videotoolbox* ]] || die "no VideoToolbox encoders"
[[ "$decoders" == *libdav1d* ]] || die "no libdav1d"
[[ "$buildconf" != *--enable-gpl* && "$buildconf" != *--enable-nonfree* ]] || die "a GPL or nonfree build"
"$U/bin/ffprobe" -hide_banner -version >/dev/null || die "ffprobe doesn't run"
say "done: $U ($(du -sh "$U" | cut -f1)): $("$U/bin/ffmpeg" -hide_banner -version | head -n 1)"
