#!/bin/sh
# Builds the ffmpeg the iPhone app links: the FFmpeg and dav1d releases
# mediaext/ffmpeg/versions.env pins for every platform, unmodified, LGPL only
# (no GPL and no nonfree component, so no software H.264 encoder), with dav1d
# for AV1 and VideoToolbox and AudioToolbox as the only encoders. Each FFmpeg
# library is FFmpeg's own shared build of it (configure --enable-shared),
# wrapped as a dynamic framework under its upstream name (libavutil,
# libswresample, libswscale, libavcodec, libavformat, libavfilter; dav1d is
# linked inside libavcodec) with only its install names changed, so a stock
# build of the same versions and configure line replaces any of them.
# HyperDrop's own C code over them is compiled into the app
# (platforms/ios/HyperDrop/Media/FFmpegDriver), never into a framework.
#
#   platforms/ios/ffmpeg/build.sh       # from anywhere; the first run takes a while
#
# Needs Xcode (the iphoneos and iphonesimulator SDKs) and, from Homebrew:
#   brew install meson ninja pkgconf
# Each step's output goes to out/<slice>/<step>.log, whose end is
# printed when the step fails.
#
# Output:  platforms/ios/ffmpeg/out/<library>.xcframework, one per library
#          (ios-arm64 and ios-arm64-simulator), git-ignored. Each slice's build
#          tree and the config.h and config_components.h guard_test.sh reads are
#          kept beside them, under out/<slice>/.
# Sources: platforms/ios/ffmpeg/out/src/, each tarball checked against its
#          SHA-256 in versions.env before it is unpacked.
#
# The privacy manifest (PrivacyInfo.xcprivacy beside this script) declares
# FileTimestamp C617.1, and goes into the frameworks in PRIVACY_LIBS: those
# whose dylib `nm -u` finds importing file-metadata APIs (fstat in libavutil's
# av_file_map, fstat and lstat in libavformat's file protocol). The build fails
# when that set changes or a library imports any other required-reason API.
# sysctl and sysctlbyname read only the CPU count and features.
#
# It does nothing when the inputs match the last successful build: the stamp
# beside the xcframeworks holds a hash of versions.env, this script, the
# privacy manifest, the clang version and the iphoneos and iphonesimulator SDK
# versions.
set -eu

HERE="$(cd "$(dirname "$0")" && pwd)"            # platforms/ios/ffmpeg
REPO="$(cd "$HERE/../../.." && pwd)"
VERSIONS="$REPO/mediaext/ffmpeg/versions.env"
. "$VERSIONS"

OUT="$HERE/out"
SRC="$OUT/src"
# The FFmpeg libraries, each its own framework.
FRAMEWORKS="libavutil libswresample libswscale libavcodec libavformat libavfilter"
PRIVACY_LIBS="libavutil libavformat"
BUNDLE_PREFIX=com.gethyperdrop.ffmpeg
STAMP="$OUT/frameworks.stamp"
PRIVACY="$HERE/PrivacyInfo.xcprivacy"
MIN_IOS=26.0
SLICES="ios-arm64 ios-arm64-simulator"
JOBS="$(sysctl -n hw.ncpu 2>/dev/null || echo 4)"

for tool in xcrun xcodebuild meson ninja pkg-config curl shasum; do
  command -v "$tool" >/dev/null 2>&1 || { echo "error: missing $tool (Xcode; brew install meson ninja pkgconf)" >&2; exit 1; }
done

fingerprint="$(
  {
    shasum -a 256 "$VERSIONS" "$HERE/build.sh" "$PRIVACY" | awk '{print $1}'
    xcrun --sdk iphoneos clang --version | sed -n 1p
    xcrun --sdk iphoneos --show-sdk-version
    xcrun --sdk iphonesimulator --show-sdk-version
  } | shasum -a 256 | awk '{print $1}'
)"
current=1
for lib in $FRAMEWORKS; do [ -d "$OUT/$lib.xcframework" ] || current=0; done
if [ "$current" = 1 ] && [ "$(cat "$STAMP" 2>/dev/null || true)" = "$fingerprint" ]; then
  echo "$OUT: $FRAMEWORKS (up to date)"
  exit 0
fi

# A slice's build tree belongs to one recipe: a changed input rebuilds every
# slice from its tarball. Downloads are kept.
[ ! -L "$OUT" ] || { echo "error: refusing to build into a symlinked $OUT" >&2; exit 1; }
rm -f "$STAMP"
rm -rf "$OUT"/*.xcframework
for slice in $SLICES; do rm -rf "${OUT:?}/$slice"; done
mkdir -p "$SRC"

# pin NAME FILE: verifies FILE against the reviewed pin in versions.env.
pin() {
  name="$1"; file="$2"
  actual="$(shasum -a 256 "$file" | awk '{print $1}')"
  expected="$(eval "echo \${${name}_SHA256}")"
  if ! printf '%s\n' "$expected" | LC_ALL=C grep -Eq '^[0-9a-f]{64}$'; then
    echo "error: ${name}_SHA256 must hold a reviewed SHA-256 pin" >&2; exit 1
  elif [ "$expected" != "$actual" ]; then
    echo "error: $file has SHA-256 $actual, versions.env says $expected" >&2; exit 1
  fi
  echo "    $(basename "$file") matches versions.env"
}

# fetch URL FILE NAME: downloads once, then pins.
fetch() {
  url="$1"; file="$2"; name="$3"
  if [ ! -s "$file" ]; then
    echo "==> downloading $url"
    curl -fsSL --retry 3 -o "$file.tmp" "$url"
    mv "$file.tmp" "$file"
  fi
  pin "$name" "$file"
}

FFMPEG_TAR="$SRC/ffmpeg-$FFMPEG_VERSION.tar.xz"
DAV1D_TAR="$SRC/dav1d-$DAV1D_VERSION.tar.xz"
fetch "https://ffmpeg.org/releases/ffmpeg-$FFMPEG_VERSION.tar.xz" "$FFMPEG_TAR" FFMPEG
fetch "https://downloads.videolan.org/pub/videolan/dav1d/$DAV1D_VERSION/dav1d-$DAV1D_VERSION.tar.xz" "$DAV1D_TAR" DAV1D

# quiet LOG COMMAND...: runs COMMAND with its output in LOG, and prints the
# end of LOG when it fails.
quiet() {
  log="$1"; shift
  "$@" >"$log" 2>&1 || { tail -40 "$log" >&2; echo "error: failed, see $log" >&2; exit 1; }
}

# slice_sdk, slice_min, slice_platform, slice_subsystem SLICE: a slice's SDK,
# deployment flag, Info.plist platform and meson subsystem.
slice_sdk() { case "$1" in ios-arm64) echo iphoneos;; ios-arm64-simulator) echo iphonesimulator;; esac; }
slice_min() { case "$1" in ios-arm64) echo "-miphoneos-version-min=$MIN_IOS";; ios-arm64-simulator) echo "-mios-simulator-version-min=$MIN_IOS";; esac; }
slice_platform() { case "$1" in ios-arm64) echo iPhoneOS;; ios-arm64-simulator) echo iPhoneSimulator;; esac; }
slice_subsystem() { case "$1" in ios-arm64) echo ios;; ios-arm64-simulator) echo ios-simulator;; esac; }

# build_dav1d SLICE: a static libdav1d into out/<slice>/prefix.
build_dav1d() {
  slice="$1"; sdk="$(slice_sdk "$slice")"; min="$(slice_min "$slice")"
  sysroot="$(xcrun --sdk "$sdk" --show-sdk-path)"
  prefix="$OUT/$slice/prefix"
  echo "==> dav1d $DAV1D_VERSION ($slice)"
  srcdir="$OUT/$slice/dav1d-src"
  mkdir -p "$srcdir"
  tar -xJf "$DAV1D_TAR" -C "$srcdir" --strip-components 1
  cross="$OUT/$slice/cross.ini"
  cat > "$cross" <<EOF
[binaries]
c = ['xcrun', '--sdk', '$sdk', 'clang', '-arch', 'arm64', '$min', '-isysroot', '$sysroot']
ar = ['xcrun', '--sdk', '$sdk', 'ar']
strip = ['xcrun', '--sdk', '$sdk', 'strip']
pkg-config = 'pkg-config'

[host_machine]
system = 'darwin'
subsystem = '$(slice_subsystem "$slice")'
kernel = 'xnu'
cpu_family = 'aarch64'
cpu = 'aarch64'
endian = 'little'
EOF
  quiet "$OUT/$slice/dav1d-setup.log" meson setup "$srcdir/build" "$srcdir" \
    --cross-file "$cross" --prefix "$prefix" --libdir lib --default-library=static --buildtype=release -Denable_tools=false \
    -Denable_tests=false -Denable_examples=false -Denable_asm=true
  quiet "$OUT/$slice/dav1d-build.log" ninja -C "$srcdir/build" install
  [ -f "$prefix/lib/pkgconfig/dav1d.pc" ] || { echo "error: dav1d ($slice) did not install its .pc file" >&2; exit 1; }
}

# The components, and nothing else, on top of --disable-everything. The
# buffer, buffersink, abuffer and abuffersink filters are part of libavfilter
# itself and are built whatever the filter list says.
PROTOCOLS=file,http,tcp
DEMUXERS=matroska,avi,mpegts,mpegps,flv,asf,ogg,mov,ivf,mxf,dv,dhav,h264,hevc,mjpeg,m4v,mpegvideo
DECODERS=vp8,vp9,libdav1d,av1,mpeg1video,mpeg2video,mpeg4,h263,msmpeg4v2,msmpeg4v3,wmv1,wmv2,wmv3,vc1,theora,flv,vp6,vp6f,vp6a,qtrle,png,prores,dnxhd,dvvideo,mjpeg,h264,hevc,aac,aac_latm,opus,vorbis,flac,ac3,eac3,dca,mp3,mp2,alac,truehd,mlp,amrnb,amrwb,wmav1,wmav2,wmapro,dvaudio,adpcm_g726,adpcm_g726le,adpcm_ima_wav,adpcm_ms,adpcm_ima_qt,pcm_s16le,pcm_s16be,pcm_s24le,pcm_s24be,pcm_s32le,pcm_s32be,pcm_f32le,pcm_f32be,pcm_f64le,pcm_s8,pcm_u8,pcm_alaw,pcm_mulaw,pcm_bluray,pcm_dvd
HWACCELS=h264_videotoolbox,hevc_videotoolbox,vp9_videotoolbox,av1_videotoolbox,mpeg1_videotoolbox,mpeg2_videotoolbox,mpeg4_videotoolbox,prores_videotoolbox
ENCODERS=h264_videotoolbox,aac_at
MUXERS=hls,mpegts,mp4
PARSERS=vp8,vp9,av1,mpegvideo,mpeg4video,h263,vc1,vp3,dnxhd,prores,mjpeg,h264,hevc,aac,aac_latm,opus,vorbis,flac,ac3,dca,mpegaudio,mlp,amr,dvaudio
BSFS=h264_mp4toannexb,hevc_mp4toannexb,aac_adtstoasc,vp9_superframe_split
FILTERS=scale,scale_vt,format,aresample,fps

# build_ffmpeg SLICE: FFmpeg's shared libraries, against dav1d's static
# archive, and their headers into out/<slice>/prefix.
build_ffmpeg() {
  slice="$1"; sdk="$(slice_sdk "$slice")"; min="$(slice_min "$slice")"
  sysroot="$(xcrun --sdk "$sdk" --show-sdk-path)"
  prefix="$OUT/$slice/prefix"
  echo "==> ffmpeg $FFMPEG_VERSION ($slice)"
  srcdir="$OUT/$slice/ffmpeg-src"
  mkdir -p "$srcdir"
  tar -xJf "$FFMPEG_TAR" -C "$srcdir" --strip-components 1
  ( cd "$srcdir" && export PKG_CONFIG_LIBDIR="$prefix/lib/pkgconfig" PKG_CONFIG_PATH="" \
    && quiet "$OUT/$slice/ffmpeg-configure.log" ./configure \
      --prefix="$prefix" --pkg-config-flags=--static \
      --enable-cross-compile --target-os=darwin --arch=aarch64 \
      --cc="xcrun --sdk $sdk clang" --sysroot="$sysroot" \
      --extra-cflags="-arch arm64 $min" \
      --extra-ldflags="-arch arm64 $min -Wl,-dead_strip -Wl,-headerpad_max_install_names" \
      --enable-shared --disable-static --enable-pic --install-name-dir=@rpath \
      --disable-everything --disable-programs --disable-doc --disable-debug --disable-avdevice \
      --disable-gpl --disable-nonfree \
      --enable-videotoolbox --enable-audiotoolbox --enable-libdav1d \
      --enable-protocol="$PROTOCOLS" --enable-demuxer="$DEMUXERS" --enable-decoder="$DECODERS" \
      --enable-hwaccel="$HWACCELS" --enable-encoder="$ENCODERS" --enable-muxer="$MUXERS" \
      --enable-parser="$PARSERS" --enable-bsf="$BSFS" --enable-filter="$FILTERS" \
    && quiet "$OUT/$slice/ffmpeg-make.log" make -j"$JOBS" install )
  cp "$srcdir/config.h" "$srcdir/config_components.h" "$OUT/$slice/"
  for lib in $FRAMEWORKS; do
    [ -f "$prefix/lib/$lib.dylib" ] || { echo "error: ffmpeg ($slice) did not install $lib.dylib" >&2; exit 1; }
  done
}

# lib_requires SLICE LIB: the other FFmpeg libraries LIB links, from the
# Requires and Requires.private lines of its pkg-config file.
lib_requires() {
  pc="$OUT/$1/prefix/lib/pkgconfig/$2.pc"
  for word in $(sed -n 's/^Requires\(\.private\)\{0,1\}: *//p' "$pc" | tr ',' ' '); do
    case " $FRAMEWORKS " in *" $word "*) printf '%s ' "$word" ;; esac
  done
}

# needs_privacy LIB: whether LIB carries the privacy manifest.
needs_privacy() { case " $PRIVACY_LIBS " in *" $1 "*) return 0 ;; esac; return 1; }

# build_framework SLICE LIB: FFmpeg's own shared LIB, as configure and make
# built it (dav1d's static archive linked into libavcodec), wrapped as
# out/<slice>/frameworks/LIB.framework with LIB's headers. Only the install
# names change: the library's own, and those of the FFmpeg libraries it loads,
# become @rpath/<library>.framework/<library>.
build_framework() {
  slice="$1"; lib="$2"; sdk="$(slice_sdk "$slice")"
  prefix="$OUT/$slice/prefix"
  fw="$OUT/$slice/frameworks/$lib.framework"
  echo "==> $lib.framework ($slice)"
  mkdir -p "$fw/Headers"
  built="$(otool -D "$prefix/lib/$lib.dylib" | sed -n 2p)"     # @rpath/libavcodec.62.dylib
  cp "$prefix/lib/${built#@rpath/}" "$fw/$lib"
  chmod u+w "$fw/$lib"
  set -- -id "@rpath/$lib.framework/$lib"
  for dep in $(otool -L "$fw/$lib" | sed -n '3,$p' | awk '{print $1}'); do
    case "$dep" in
      @rpath/lib*.dylib) name="${dep#@rpath/}"; name="${name%%.*}"
        set -- "$@" -change "$dep" "@rpath/$name.framework/$name" ;;
    esac
  done
  quiet "$OUT/$slice/install-name-$lib.log" xcrun --sdk "$sdk" install_name_tool "$@" "$fw/$lib"
  xcrun --sdk "$sdk" strip -x "$fw/$lib" 2>/dev/null
  cp -R "$prefix/include/$lib/" "$fw/Headers/"
  # The manifest declares FileTimestamp: the library must import exactly the
  # file-metadata APIs it covers, and none of the other required-reason APIs.
  imports="$(nm -u "$fw/$lib" | sed 's/\$INODE64$//')"
  if printf '%s\n' "$imports" | LC_ALL=C grep -Eqx '_(mach_absolute_time|mach_continuous_time|statfs|fstatfs|statvfs|fstatvfs)'; then
    echo "error: $lib imports a required-reason API PrivacyInfo.xcprivacy does not declare" >&2; exit 1
  fi
  if printf '%s\n' "$imports" | LC_ALL=C grep -Eqx '_(stat|fstat|lstat|fstatat|getattrlist|getattrlistbulk|fgetattrlist|getattrlistat)'; then
    needs_privacy "$lib" || { echo "error: $lib reads file metadata but is not in PRIVACY_LIBS" >&2; exit 1; }
  else
    ! needs_privacy "$lib" || { echo "error: $lib is in PRIVACY_LIBS but reads no file metadata" >&2; exit 1; }
  fi
  if needs_privacy "$lib"; then cp "$PRIVACY" "$fw/PrivacyInfo.xcprivacy"; fi
  cat > "$fw/Info.plist" <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>CFBundleDevelopmentRegion</key>
	<string>en</string>
	<key>CFBundleExecutable</key>
	<string>$lib</string>
	<key>CFBundleIdentifier</key>
	<string>$BUNDLE_PREFIX.$lib</string>
	<key>CFBundleInfoDictionaryVersion</key>
	<string>6.0</string>
	<key>CFBundleName</key>
	<string>$lib</string>
	<key>CFBundlePackageType</key>
	<string>FMWK</string>
	<key>CFBundleShortVersionString</key>
	<string>$FFMPEG_VERSION</string>
	<key>CFBundleVersion</key>
	<string>$FFMPEG_VERSION</string>
	<key>CFBundleSupportedPlatforms</key>
	<array>
		<string>$(slice_platform "$slice")</string>
	</array>
	<key>MinimumOSVersion</key>
	<string>$MIN_IOS</string>
</dict>
</plist>
EOF
  plutil -lint "$fw/Info.plist" >/dev/null
  # The dylib loads only the system's own libraries and frameworks and the
  # FFmpeg libraries it requires.
  for dep in $(otool -L "$fw/$lib" | sed -n '2,$p' | awk '{print $1}'); do
    case "$dep" in
      /usr/lib/*|/System/Library/Frameworks/*) ;;
      @rpath/*.framework/*)
        name="${dep#@rpath/}"; name="${name%%.framework/*}"
        case " $lib $(lib_requires "$slice" "$lib") " in
          *" $name "*) ;;
          *) echo "error: $fw/$lib loads $dep, which its pkg-config file does not require" >&2; exit 1 ;;
        esac ;;
      *) echo "error: $fw/$lib loads $dep" >&2; exit 1 ;;
    esac
  done
}

for slice in $SLICES; do
  build_dav1d "$slice"
  build_ffmpeg "$slice"
  for lib in $FRAMEWORKS; do build_framework "$slice" "$lib"; done
done

for lib in $FRAMEWORKS; do
  echo "==> $lib.xcframework"
  args=""
  for slice in $SLICES; do args="$args -framework $OUT/$slice/frameworks/$lib.framework"; done
  # shellcheck disable=SC2086 # a list of arguments without spaces
  xcodebuild -create-xcframework $args -output "$OUT/$lib.xcframework" >/dev/null
done
"$HERE/guard_test.sh" "$OUT"
printf '%s\n' "$fingerprint" > "$STAMP"
echo "$OUT: $FRAMEWORKS (FFmpeg $FFMPEG_VERSION, dav1d $DAV1D_VERSION)"
