#!/bin/zsh
# FFMPEG FOR JOMBO'S VIDEO EDITS: WebM, MKV, AVI, MPEG-1/2 and other videos iPhone can't open, made into an ordinary MP4 on the
# phone (the owner, 20 Nov 2026: "if that makes it better then add it"). Builds Packages/VeyroKit/Frameworks/FFmpeg.xcframework:
# one dynamic framework (so it can be swapped, as the LGPL asks) for iPhone, the iPhone simulator and the Mac (VeyroKit's tests).
#
# Unmodified FFmpeg 9.0.2 (https://ffmpeg.org/releases/ffmpeg-9.0.2.tar.xz, signed by FFmpeg's release key
# FCF986EA15E6E293A5644F10B4322F04D67658D8), LGPL 2.1 or later: no GPL or "nonfree" parts. Only what reading those files needs:
#   - containers: Matroska/WebM, AVI, MPEG-TS, MPEG-PS, MPEG video, FLV, Ogg, MP4/MOV; written: MP4.
#   - pictures decoded: VP8, VP9, MPEG-1, MPEG-2, MPEG-4 Part 2 (Xvid, DivX), MS-MPEG-4 v1–3, H.263, Sorenson (FLV), Theora,
#     Motion JPEG.
#     H.264, HEVC and AV1 are never decoded here: they're copied as they are into the MP4, and the phone's own decoder plays them.
#     (No software H.264/HEVC decoder: their patent pools are still licensing. No WMV/VC-1.)
#   - sound decoded: Vorbis, Opus, MP2, MP3, AC-3, FLAC, PCM, ADPCM; AAC by Apple's own decoder (aac_at), only so FFmpeg can read
#     an MPEG stream's AAC (its parser leaves the rate and channels unset on purpose). AAC, AC-3, E-AC-3 and ALAC are copied; MP3
#     is made AAC (AVFoundation doesn't list MP3 inside an MP4).
#   - written with Apple's own encoders through VideoToolbox and AudioToolbox (h264_videotoolbox, aac_at).
#
#   zsh tools/ffmpeg/build.sh <unpacked ffmpeg-9.0.2 folder> <scratch folder>
set -euo pipefail
SRC=${1:?ffmpeg source folder}
WORK=${2:?scratch folder}
REPO=${REPO:-${0:A:h:h:h}}
OUT=$REPO/Packages/VeyroKit/Frameworks/FFmpeg.xcframework
HEADERS=$REPO/Packages/VeyroKit/Sources/VeyroFF/ffmpeg
JOBS=${JOBS:-6}

COMMON=(
  --disable-everything --disable-programs --disable-doc --disable-debug --disable-network --disable-autodetect
  --disable-avdevice --disable-avfilter --enable-pic --enable-static --disable-shared
  --enable-avformat --enable-avcodec --enable-swscale --enable-swresample
  --enable-videotoolbox --enable-audiotoolbox --enable-zlib
  --enable-protocol=file
  --enable-demuxer=matroska,avi,mpegts,mpegps,mpegvideo,flv,ogg,mov,m4v,h264,hevc
  --enable-muxer=mp4
  --enable-parser=h264,hevc,av1,mpeg4video,mpegvideo,vp8,vp9,mpegaudio,aac,ac3,opus,vorbis,flac,mjpeg,h263
  --enable-decoder=vp8,vp9,mpeg1video,mpeg2video,mpeg4,msmpeg4v1,msmpeg4v2,msmpeg4v3,h263,flv,theora,mjpeg
  --enable-decoder=vorbis,opus,mp2,mp2float,mp3,mp3float,ac3,flac,pcm_s16le,pcm_s16be,pcm_s24le,pcm_s32le,pcm_f32le,pcm_u8,pcm_alaw,pcm_mulaw,adpcm_ima_wav,adpcm_ms,aac_at
  --enable-encoder=h264_videotoolbox,aac_at
  --enable-bsf=aac_adtstoasc,mpeg4_unpack_bframes,vp9_superframe_split,extract_extradata
)

# slice <name> <sdk> <target triple> <framework layout: shallow|deep> <min OS flag>
slice() {
  local name=$1 sdk=$2 triple=$3 layout=$4
  local sysroot=$(xcrun -sdk $sdk --show-sdk-path) cc=$(xcrun -sdk $sdk -f clang)
  local build=$WORK/build-$name prefix=$WORK/out-$name
  rm -rf $build $prefix && mkdir -p $build
  (cd $build && $SRC/configure --prefix=$prefix --enable-cross-compile --target-os=darwin --arch=aarch64 \
      --cc=$cc --sysroot=$sysroot --extra-cflags="-target $triple" --extra-ldflags="-target $triple" \
      "${COMMON[@]}" > configure.log 2>&1 || { tail -30 configure.log; exit 1; })
  (cd $build && make -j$JOBS > make.log 2>&1 && make install > install.log 2>&1) || { tail -30 $build/make.log; exit 1; }

  # One dynamic library from the five, as a framework.
  local fw=$WORK/fw-$name/FFmpeg.framework bin res
  rm -rf $WORK/fw-$name && mkdir -p $fw
  if [[ $layout == deep ]]; then
    mkdir -p $fw/Versions/A/Resources; bin=$fw/Versions/A/FFmpeg; res=$fw/Versions/A/Resources
  else
    bin=$fw/FFmpeg; res=$fw
  fi
  $cc -dynamiclib -target $triple -isysroot $sysroot -install_name @rpath/FFmpeg.framework/$([[ $layout == deep ]] && echo Versions/A/)FFmpeg \
    -compatibility_version 9.0 -current_version 9.0.2 -Wl,-all_load \
    $prefix/lib/libavformat.a $prefix/lib/libavcodec.a $prefix/lib/libswresample.a $prefix/lib/libswscale.a $prefix/lib/libavutil.a \
    -framework VideoToolbox -framework AudioToolbox -framework CoreMedia -framework CoreVideo -framework CoreFoundation -lz -o $bin
  strip -x $bin
  local minos=$(xcrun vtool -show-build $bin 2>/dev/null | awk '/minos/ {print $2; exit}')
  local platform=$([[ $sdk == macosx ]] && echo MacOSX || ([[ $sdk == iphonesimulator ]] && echo iPhoneSimulator || echo iPhoneOS))
  cat > $res/Info.plist <<PLIST
<?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>FFmpeg</string>
  <key>CFBundleIdentifier</key><string>com.samneon.veyro3.ffmpeg</string>
  <key>CFBundleInfoDictionaryVersion</key><string>6.0</string>
  <key>CFBundleName</key><string>FFmpeg</string>
  <key>CFBundlePackageType</key><string>FMWK</string>
  <key>CFBundleShortVersionString</key><string>9.0.2</string>
  <key>CFBundleVersion</key><string>9.0.2</string>
  <key>CFBundleSupportedPlatforms</key><array><string>$platform</string></array>
  $([[ $sdk == macosx ]] && echo "<key>LSMinimumSystemVersion</key><string>$minos</string>" || echo "<key>MinimumOSVersion</key><string>$minos</string>")
</dict></plist>
PLIST
  # (It reads the length of the file it's given, inside the app's own folders: Apple's "required reason" C617.1.)
  cat > $res/PrivacyInfo.xcprivacy <<'PRIV'
<?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>NSPrivacyTracking</key><false/>
  <key>NSPrivacyTrackingDomains</key><array/>
  <key>NSPrivacyCollectedDataTypes</key><array/>
  <key>NSPrivacyAccessedAPITypes</key><array><dict>
    <key>NSPrivacyAccessedAPIType</key><string>NSPrivacyAccessedAPICategoryFileTimestamp</string>
    <key>NSPrivacyAccessedAPITypeReasons</key><array><string>C617.1</string></array>
  </dict></array>
</dict></plist>
PRIV
  # (Its licence goes with it inside the app, as the LGPL asks: LGPL 2.1, FFmpeg's own copy.)
  cp $SRC/COPYING.LGPLv2.1 $res/LICENSE.txt
  if [[ $layout == deep ]]; then
    (cd $fw/Versions && ln -s A Current) && (cd $fw && ln -s Versions/Current/FFmpeg FFmpeg && ln -s Versions/Current/Resources Resources)
  fi
  echo "$name: $(du -sh $fw | cut -f1)"
}

slice ios iphoneos arm64-apple-ios18.0 shallow
slice sim iphonesimulator arm64-apple-ios18.0-simulator shallow
slice mac macosx arm64-apple-macos15.0 deep

rm -rf $OUT
xcodebuild -create-xcframework -framework $WORK/fw-ios/FFmpeg.framework -framework $WORK/fw-sim/FFmpeg.framework \
  -framework $WORK/fw-mac/FFmpeg.framework -output $OUT > /dev/null
# (Its public headers, for VeyroFF, the C that drives it. The same on every slice: all three are 64-bit Arm.)
rm -rf $HEADERS && mkdir -p $HEADERS && cp -R $WORK/out-ios/include/ $HEADERS/
cp $SRC/COPYING.LGPLv2.1 ${OUT:h}/FFmpeg-LICENSE.txt
echo "FFmpeg.xcframework: $(du -sh $OUT | cut -f1)"
