#!/usr/bin/env bash
# =============================================================================
# The camera worker's FFmpeg: our own LGPL-2.1-or-later build with OpenH264,
# from pinned, checksum-verified upstream sources.
#
#   xtask/ffmpeg-lgpl.sh <prefix> [<work dir>]
#
# Builds OpenH264 and a minimal FFmpeg (only libavcodec, libavformat,
# libavutil and libswscale; only the libopenh264 encoder, the MP4 muxer and
# the file protocol) into <prefix>, as shared libraries. Always a NATIVE build
# for the machine it runs on:
#   Linux    x86_64 .so files      (releases: inside xtask/linux-builder.Dockerfile)
#   macOS    host-arch .dylib files (arm64 or x86_64)
#   Windows  x64 DLLs + import .lib files, built with MSVC (cl.exe) from an
#            MSYS2 bash that inherits a Visual Studio developer environment
#
# `cargo xtask ffmpeg` runs this into .tools/ffmpeg-lgpl/<os>-<arch>-<hash>/
# (the hash covers this file, so editing it means a rebuild) and every desktop
# build reuses that directory. The prefix must not move after the build: the
# pkg-config files and macOS install names record it.
#
# Never add --enable-gpl, --enable-nonfree or --enable-version3, and never an
# external library other than OpenH264: `cargo xtask` refuses to bundle a
# library whose licence is not "LGPL version 2.1 or later"
# (xtask/src/ffmpeg_licence.rs). This file is the build instructions
# published with the source offer.
# =============================================================================
set -euo pipefail

FFMPEG_VERSION=7.1.5
FFMPEG_SHA256=de668509caf9e35e3cd162473441fdb29538c6d96ed080292b3cf9e6fc5d558f
OPENH264_VERSION=2.6.0
OPENH264_SHA256=558544ad358283a7ab2930d69a9ceddf913f4a51ee9bf1bfb9e377322af81a69

[[ $# -ge 1 ]] || { echo "usage: $0 <prefix> [<work dir>]" >&2; exit 2; }
prefix="$1"
work="${2:-$(mktemp -d)}"
case "$(uname -s)" in
# Windows paths arrive as C:/…; tar reads "C:" as a remote host, so use the MSYS form.
MINGW* | MSYS*) prefix="$(cygpath -u "$prefix")" work="$(cygpath -u "$work")" ;;
esac
mkdir -p "$prefix" "$work"
jobs="$(getconf _NPROCESSORS_ONLN 2>/dev/null || sysctl -n hw.ncpu 2>/dev/null || echo 4)"
self="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/$(basename "${BASH_SOURCE[0]}")"

sha256_ok() { # sha256 file
    if command -v sha256sum >/dev/null; then echo "$1  $2" | sha256sum -c --status -
    else echo "$1  $2" | shasum -a 256 -c --status -; fi
}
fetch() { # url sha256 out; a matching file from an earlier run is reused
    if [[ -f "$3" ]] && sha256_ok "$2" "$3"; then return 0; fi
    curl --proto '=https' --tlsv1.2 -fsSL --retry 3 -o "$3.part" "$1"
    sha256_ok "$2" "$3.part" || { echo "checksum mismatch for $1" >&2; rm -f "$3.part"; exit 1; }
    mv "$3.part" "$3"
}
fetch "https://ffmpeg.org/releases/ffmpeg-${FFMPEG_VERSION}.tar.xz" "$FFMPEG_SHA256" "$work/ffmpeg-${FFMPEG_VERSION}.tar.xz"
fetch "https://github.com/cisco/openh264/archive/refs/tags/v${OPENH264_VERSION}.tar.gz" "$OPENH264_SHA256" "$work/openh264-${OPENH264_VERSION}.tar.gz"
rm -rf "$work/ffmpeg-${FFMPEG_VERSION}" "$work/openh264-${OPENH264_VERSION}"
tar -xf "$work/ffmpeg-${FFMPEG_VERSION}.tar.xz" -C "$work"
tar -xzf "$work/openh264-${OPENH264_VERSION}.tar.gz" -C "$work"
ff="$work/ffmpeg-${FFMPEG_VERSION}"
oh="$work/openh264-${OPENH264_VERSION}"

# The common part of the configure line. Everything off, then exactly what
# the worker uses (security/camera-worker/src/recording/h264.rs).
common=(
    --enable-shared --disable-static
    --disable-programs --disable-doc --disable-debug
    --disable-autodetect
    --disable-everything
    --disable-avdevice --disable-avfilter --disable-swresample --disable-network
    --enable-libopenh264 --enable-encoder=libopenh264
    --enable-muxer=mp4 --enable-protocol=file
)

# OpenH264 is always built with its assembly (nasm): without it, its rate
# control is not deterministic (the same input gave 310 to 1980 kb/s).
os="$(uname -s)"
case "$os" in
Linux)
    platform="linux-$(uname -m)"
    install_prefix="$prefix"
    make -C "$oh" -j"$jobs" OS=linux ARCH="$(uname -m)" PREFIX="$install_prefix" \
        BUILDTYPE=Release DEBUGSYMBOLS=False install-shared
    extra=(--enable-pthreads)
    ;;
Darwin)
    platform="macos-$(uname -m)"
    install_prefix="$prefix"
    export MACOSX_DEPLOYMENT_TARGET="${MACOSX_DEPLOYMENT_TARGET:-11.0}"
    make -C "$oh" -j"$jobs" OS=darwin ARCH="$(uname -m)" PREFIX="$install_prefix" \
        BUILDTYPE=Release DEBUGSYMBOLS=False install-shared
    extra=(--enable-pthreads
           --extra-cflags="-mmacosx-version-min=${MACOSX_DEPLOYMENT_TARGET}"
           --extra-ldflags="-mmacosx-version-min=${MACOSX_DEPLOYMENT_TARGET}")
    ;;
MINGW*|MSYS*)
    platform="windows-x86_64"
    command -v cl.exe >/dev/null || {
        echo "ffmpeg-lgpl.sh: cl.exe is not on PATH. Run from an MSYS2 bash started with" >&2
        echo "MSYS2_PATH_TYPE=inherit inside a Visual Studio x64 developer environment" >&2
        echo "(cargo xtask ffmpeg does this for you)." >&2
        exit 1
    }
    # MSYS2's coreutils `link` must not shadow MSVC's link.exe.
    PATH="$(dirname "$(command -v cl.exe)"):$PATH"; export PATH
    # cl and link want C:/... paths; MSYS2's make and install accept them too.
    install_prefix="$(cygpath -m "$prefix")"
    # A static openh264.lib linked into avcodec-61.dll, with the same dynamic
    # CRT (-MD) as FFmpeg and the Rust worker. OpenH264's own MSVC flags,
    # minus -MT and the PDB.
    make -C "$oh" -j"$jobs" OS=msvc ARCH=x86_64 PREFIX="$install_prefix" \
        BUILDTYPE=Release DEBUGSYMBOLS=False \
        CFLAGS_OPT="-O2 -Ob1 -Oy- -FS -GF -GS -Gy -DNDEBUG -MD" install-static
    extra=(--toolchain=msvc --target-os=win64 --arch=x86_64
           --enable-w32threads --extra-cflags=-MD)
    ;;
*) echo "ffmpeg-lgpl.sh: unsupported host $os" >&2; exit 1 ;;
esac

cd "$ff"
PKG_CONFIG_PATH="$prefix/lib/pkgconfig" ./configure --prefix="$install_prefix" "${common[@]}" "${extra[@]}"
make -j"$jobs"
make install

if [[ "$platform" == windows-* ]]; then
    # MSVC builds put the import libraries (avcodec.lib, ...) beside the DLLs
    # in bin/; ffmpeg-sys-next reads FFMPEG_DIR/lib.
    cp "$prefix"/bin/*.lib "$prefix/lib/"
fi

# Self-describing output: the licence texts, this script, and what was built.
cp "$ff/COPYING.LGPLv2.1" "$prefix/LICENSE-FFmpeg-LGPL-2.1.txt"
cp "$oh/LICENSE" "$prefix/LICENSE-OpenH264.txt"
cp "$self" "$prefix/ffmpeg-lgpl.sh.tmp"
{
    echo "FFmpeg ${FFMPEG_VERSION} (https://ffmpeg.org/releases/ffmpeg-${FFMPEG_VERSION}.tar.xz, sha256 ${FFMPEG_SHA256}), unmodified"
    echo "OpenH264 ${OPENH264_VERSION} (https://github.com/cisco/openh264/archive/refs/tags/v${OPENH264_VERSION}.tar.gz, sha256 ${OPENH264_SHA256}), unmodified"
    echo "platform: ${platform}"
    echo "configure: $(grep -m1 '^FFMPEG_CONFIGURATION=' ffbuild/config.mak | cut -d= -f2- | sed "s|$install_prefix|<prefix>|g")"
    echo "license: $(grep -m1 'define FFMPEG_LICENSE' config.h | cut -d'"' -f2)"
    echo "build script: xtask/ffmpeg-lgpl.sh (copy beside this file)"
} > "$prefix/FFMPEG-BUILD.txt"
# Written last: its presence marks a complete build (xtask/src/ffmpeg.rs).
mv "$prefix/ffmpeg-lgpl.sh.tmp" "$prefix/ffmpeg-lgpl.sh"
cat "$prefix/FFMPEG-BUILD.txt"
