#!/bin/bash
# Configure and build the FFmpeg 9.1 libraries for WebAssembly (single-threaded,
# SIMD128). Installs headers and static libraries into /opt/ffmpeg.
set -euo pipefail
. /env.sh
. /components.sh

mkdir -p /build/ffmpeg && tar -xf /tmp/ffmpeg-9.1.tar.xz -C /build/ffmpeg --strip-components=1
cd /build/ffmpeg

# Nothing in this build may enable shared memory (-pthread): the engine must
# run without SharedArrayBuffer so the page needs no cross-origin isolation.
if grep -q -- '-pthread' "$PREFIX"/lib/pkgconfig/*.pc; then
  echo "a dependency asks for -pthread:"; grep -l -- '-pthread' "$PREFIX"/lib/pkgconfig/*.pc; exit 1
fi

emconfigure ./configure \
  --prefix=/opt/ffmpeg \
  --target-os=none --arch=wasm32 --enable-cross-compile \
  --disable-x86asm --disable-inline-asm --disable-runtime-cpudetect --disable-autodetect \
  --disable-pthreads --disable-w32threads --disable-os2threads \
  --disable-stripping --disable-programs --disable-doc --disable-debug \
  --disable-network --disable-avdevice \
  --nm=emnm --ar=emar --ranlib=emranlib --cc=emcc --cxx=em++ --objcc=emcc --dep-cc=emcc \
  --pkg-config=pkg-config --pkg-config-flags=--static \
  --extra-cflags="-I$PREFIX/include $OPT_FLAGS" \
  --extra-cxxflags="-I$PREFIX/include $OPT_FLAGS" \
  --extra-ldflags="-L$PREFIX/lib $SIMD_FLAGS -fwasm-exceptions" \
  --enable-gpl \
  --enable-libx264 --enable-libvpx --enable-libopus --enable-libmp3lame \
  --enable-libdav1d --enable-libzimg --enable-zlib \
  --disable-everything \
  --enable-decoder="$DECODERS" \
  --enable-encoder="$ENCODERS" \
  --enable-demuxer="$DEMUXERS" \
  --enable-muxer="$MUXERS" \
  --enable-parser="$PARSERS" \
  --enable-bsf="$BSFS" \
  --enable-filter="$FILTERS" \
  --enable-protocol="$PROTOCOLS" \
  || { tail -80 ffbuild/config.log; exit 1; }

# Sanity checks on the configuration.
grep -q '^#define HAVE_PTHREADS 0' config.h || { echo "pthreads must be off"; exit 1; }
grep -q '^#define HAVE_SIMD128 1' config.h || { echo "SIMD128 must be on"; exit 1; }
for c in CONFIG_LIBX264_ENCODER CONFIG_LIBVPX_VP9_ENCODER CONFIG_LIBOPUS_ENCODER CONFIG_LIBMP3LAME_ENCODER \
         CONFIG_LIBDAV1D_DECODER CONFIG_HEVC_DECODER CONFIG_ZSCALE_FILTER CONFIG_MOV_MUXER; do
  grep -q "^#define $c 1" config_components.h || { echo "$c is off"; exit 1; }
done

emmake make -j"$JOBS"
emmake make install

# Record the exact configuration next to the libraries (published with the
# source code for GPL compliance).
mkdir -p /opt/ffmpeg/share
cp ffbuild/config.mak /opt/ffmpeg/share/ffmpeg-config.mak
sed -n 's/^#define FFMPEG_VERSION "\(.*\)"/\1/p' libavutil/ffversion.h > /opt/ffmpeg/share/ffmpeg-version.txt
grep -E '^#define FFMPEG_CONFIGURATION' config.h > /opt/ffmpeg/share/ffmpeg-configuration.txt
