#!/bin/sh
# Builds the FFmpeg libraries clipson uses into vendor/ffmpeg: the hardware
# video encoders, the AAC encoder and the MP4 muxer. Nothing else.
#
# Run in an MSYS2 UCRT64 shell. Packages:
#   pacman -S make diffutils git mingw-w64-ucrt-x86_64-gcc mingw-w64-ucrt-x86_64-nasm \
#             mingw-w64-ucrt-x86_64-pkgconf mingw-w64-ucrt-x86_64-amf-headers
set -eu

FFMPEG_TAG=n9.0
# Branch of nv-codec-headers. It sets the oldest NVIDIA driver NVENC runs on:
# sdk/11.1: 471.41, no AV1.  sdk/12.0: 522.25.  sdk/12.1: 531.61.  sdk/13.0: 570.0.
NVENC_HEADERS=${NVENC_HEADERS:-sdk/12.0}

root=$(cd "$(dirname "$0")/.." && pwd)
work=${CLIPSON_FFMPEG_WORK:-$root/target/ffmpeg-build}
out=$root/vendor/ffmpeg

mkdir -p "$work"
[ -d "$work/ffmpeg" ] ||
    git clone --depth 1 --branch "$FFMPEG_TAG" https://github.com/FFmpeg/FFmpeg.git "$work/ffmpeg"
[ -d "$work/nv-codec-headers" ] ||
    git clone --depth 1 --branch "$NVENC_HEADERS" https://github.com/FFmpeg/nv-codec-headers.git "$work/nv-codec-headers"
make -C "$work/nv-codec-headers" install PREFIX="$work/prefix"
export PKG_CONFIG_PATH="$work/prefix/lib/pkgconfig"

mkdir -p "$work/build"
cd "$work/build"
# The DLLs shall depend on Windows system libraries only: w32threads, libgcc and
# winpthread (pulled in by clock_gettime) linked statically.
"$work/ffmpeg/configure" \
    --prefix="$work/install" \
    --disable-everything --disable-autodetect --disable-programs --disable-doc --disable-network \
    --disable-avdevice --disable-avfilter --disable-swscale --disable-swresample \
    --enable-shared --disable-static \
    --enable-w32threads --enable-d3d11va --enable-amf --enable-ffnvcodec --enable-nvenc \
    --enable-encoder=aac,h264_amf,hevc_amf,av1_amf,h264_nvenc,hevc_nvenc,av1_nvenc \
    --enable-muxer=mp4 --enable-protocol=file \
    --extra-ldflags=-static-libgcc \
    --extra-libs="-Wl,-Bstatic -lwinpthread -Wl,-Bdynamic"
make -j"$(nproc)"
make install

# Layout expected by FFMPEG_DIR: bin (DLLs), lib (import libraries), include.
rm -rf "$out"
mkdir -p "$out/bin" "$out/lib"
cp "$work/install/bin/"*.dll "$out/bin/"
cp "$work/install/bin/"*.lib "$out/lib/"
cp -r "$work/install/include" "$out/"
cp "$work/ffmpeg/COPYING.LGPLv2.1" "$out/LICENSE.txt"
ls -l "$out/bin"
