#!/usr/bin/env bash
# Cross-compiles a small, static, LGPL ffmpeg.exe + ffprobe.exe for Windows x64
# on the Ubuntu VPS. Only what yt-dlp needs: all demuxers/decoders/muxers,
# a short list of encoders (MP3/AAC/FLAC/ALAC, thumbnails, subtitles), schannel TLS.
# Output: $WORK/out/bin/{ffmpeg,ffprobe}.exe   (~25 MB each instead of ~130 MB)
set -euo pipefail

FFMPEG_TAG="${FFMPEG_TAG:-n8.1.3}"
LAME_VER=3.100
ZLIB_VER=1.3.1
WORK="${WORK:-/root/ffbuild/win64}"
PREFIX="$WORK/out"
HOST=x86_64-w64-mingw32
JOBS="$(nproc)"

export DEBIAN_FRONTEND=noninteractive
if ! command -v "$HOST-gcc" >/dev/null || ! command -v nasm >/dev/null; then
  apt-get update -qq
  apt-get install -y -qq mingw-w64 nasm make pkg-config curl xz-utils >/dev/null
fi

mkdir -p "$WORK/src" "$PREFIX"
cd "$WORK/src"

# --- zlib (png thumbnails need it) ---
if [ ! -f "$PREFIX/lib/libz.a" ]; then
  curl -fsSL "https://zlib.net/fossils/zlib-$ZLIB_VER.tar.gz" -o zlib.tgz
  rm -rf "zlib-$ZLIB_VER" && tar xzf zlib.tgz
  (cd "zlib-$ZLIB_VER" &&
    make -f win32/Makefile.gcc PREFIX="$HOST-" -j"$JOBS" libz.a >/dev/null &&
    install -D -m644 libz.a "$PREFIX/lib/libz.a" &&
    install -D -m644 zlib.h "$PREFIX/include/zlib.h" &&
    install -D -m644 zconf.h "$PREFIX/include/zconf.h")
fi

# --- LAME (MP3 encoder, LGPL) ---
if [ ! -f "$PREFIX/lib/libmp3lame.a" ]; then
  curl -fsSL "http://deb.debian.org/debian/pool/main/l/lame/lame_$LAME_VER.orig.tar.gz" -o lame.tgz
  rm -rf "lame-$LAME_VER" && tar xzf lame.tgz
  (cd "lame-$LAME_VER" &&
    ./configure --host="$HOST" --prefix="$PREFIX" --enable-static --disable-shared \
      --disable-frontend --disable-decoder --enable-nasm >/dev/null &&
    make -j"$JOBS" >/dev/null && make install >/dev/null)
fi

# --- GPU vendor encoders (all MIT licensed; FFmpeg stays LGPL) ---
# NVIDIA NVENC: header-only, loads nvEncodeAPI64.dll from the driver at runtime
if [ ! -f "$PREFIX/include/ffnvcodec/nvEncodeAPI.h" ]; then
  rm -rf nv-codec-headers && git clone -q --depth 1 https://github.com/FFmpeg/nv-codec-headers.git
  make -C nv-codec-headers PREFIX="$PREFIX" install >/dev/null
fi
# AMD AMF: header-only, loads amfrt64.dll from the driver at runtime
if [ ! -f "$PREFIX/include/AMF/core/Factory.h" ]; then
  rm -rf AMF && git clone -q --depth 1 --filter=blob:none --sparse https://github.com/GPUOpen-LibrariesAndSDKs/AMF.git
  (cd AMF && git sparse-checkout set amf/public/include >/dev/null)
  mkdir -p "$PREFIX/include/AMF" && cp -r AMF/amf/public/include/* "$PREFIX/include/AMF/"
fi
# Intel Quick Sync: oneVPL dispatcher (static), finds the GPU runtime from the driver
if [ ! -f "$PREFIX/lib/libvpl.a" ]; then
  rm -rf libvpl build-vpl && git clone -q --depth 1 https://github.com/intel/libvpl.git
  cat > mingw.cmake <<EOF
set(CMAKE_SYSTEM_NAME Windows)
set(CMAKE_C_COMPILER $HOST-gcc)
set(CMAKE_CXX_COMPILER $HOST-g++)
set(CMAKE_RC_COMPILER $HOST-windres)
set(CMAKE_FIND_ROOT_PATH /usr/$HOST $PREFIX)
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
EOF
  cmake -S libvpl -B build-vpl -DCMAKE_TOOLCHAIN_FILE="$PWD/mingw.cmake" -DCMAKE_BUILD_TYPE=Release \
    -DCMAKE_INSTALL_PREFIX="$PREFIX" -DCMAKE_INSTALL_LIBDIR=lib -DBUILD_SHARED_LIBS=OFF \
    -DBUILD_TESTS=OFF -DBUILD_EXAMPLES=OFF -DINSTALL_EXAMPLES=OFF -DBUILD_TOOLS=OFF -DINSTALL_DEV=ON >/dev/null
  cmake --build build-vpl -j"$JOBS" >/dev/null && cmake --install build-vpl >/dev/null
  # static C++ dispatcher: ffmpeg's link test needs the C++ runtime too
  sed -i -E 's/^(Libs: .*)$/\1 -lstdc++/' "$PREFIX/lib/pkgconfig/vpl.pc"
fi

# --- FFmpeg ---
if [ ! -d "ffmpeg-$FFMPEG_TAG" ]; then
  git clone -q --depth 1 -b "$FFMPEG_TAG" https://github.com/FFmpeg/FFmpeg.git "ffmpeg-$FFMPEG_TAG"
fi
cd "ffmpeg-$FFMPEG_TAG"
make distclean >/dev/null 2>&1 || true

# audio + subtitles + thumbnails, plus video encoders for the converter:
# h264_mf/hevc_mf = Windows Media Foundation (OS codec, GPU with -hw_encoding 1), mpeg4/h263 for AVI and 3GP.
# h264_qsv / h264_nvenc / h264_amf = native Intel / NVIDIA / AMD encoders (2-4x faster than h264_mf).
# D3D11VA hwaccels = GPU decoding of H.264/HEVC/VP9/AV1 (converter: -hwaccel d3d11va, zero-copy into h264_mf).
ENCODERS="aac,alac,flac,libmp3lame,mjpeg,png,bmp,gif,pcm_s16le,pcm_s24le,mov_text,srt,subrip,ass,ssa,webvtt,text,opus,vorbis,mpeg4,h263,h263p,mpeg2video,h264_mf,hevc_mf,h264_qsv,hevc_qsv,h264_nvenc,hevc_nvenc,h264_amf,hevc_amf,rawvideo,wrapped_avframe"

PKG_CONFIG_PATH="$PREFIX/lib/pkgconfig" ./configure \
  --prefix="$PREFIX" \
  --arch=x86_64 --target-os=mingw32 --cross-prefix="$HOST-" \
  --pkg-config=pkg-config --pkg-config-flags=--static \
  --enable-static --disable-shared \
  --disable-autodetect --enable-w32threads --enable-schannel --enable-zlib --enable-mediafoundation --enable-d3d11va \
  --enable-libvpl --enable-ffnvcodec --enable-nvenc --enable-amf \
  --enable-libmp3lame \
  --disable-debug --disable-doc --disable-ffplay \
  --disable-indevs --disable-outdevs --disable-hwaccels \
  --enable-hwaccel=h264_d3d11va,h264_d3d11va2,hevc_d3d11va,hevc_d3d11va2,vp9_d3d11va,vp9_d3d11va2,av1_d3d11va,av1_d3d11va2,mpeg2_d3d11va,mpeg2_d3d11va2 \
  --disable-encoders --enable-encoder="$ENCODERS" \
  --extra-cflags="-I$PREFIX/include -O2" \
  --extra-ldflags="-L$PREFIX/lib -static" \
  --extra-version="omni4" >"$WORK/configure.log" 2>&1 || { tail -40 "$WORK/configure.log"; exit 1; }

make -j"$JOBS" >"$WORK/make.log" 2>&1 || { tail -60 "$WORK/make.log"; exit 1; }
make install >/dev/null
"$HOST-strip" "$PREFIX/bin/ffmpeg.exe" "$PREFIX/bin/ffprobe.exe"
ls -la "$PREFIX/bin/"*.exe
echo "BUILD OK $FFMPEG_TAG"
