#!/bin/bash
# Compile ffw.c and link it with the FFmpeg libraries into ffw.mjs + ffw.wasm.
set -euo pipefail
. /env.sh

FF=/opt/ffmpeg
export PKG_CONFIG_PATH="$FF/lib/pkgconfig:$PKG_CONFIG_PATH"
LIBS="$(pkg-config --static --libs libavformat libavfilter libavcodec libswscale libswresample libavutil)"
if echo "$LIBS" | grep -q -- '-pthread'; then echo "a library asks for -pthread"; exit 1; fi

mkdir -p /out /build/ffw
emcc $OPT_FLAGS -Wall -Wno-deprecated-declarations -I"$FF/include" -c /ffw/ffw.c -o /build/ffw/ffw.o

# em++ links zimg's C++ runtime. One instance runs one job (fresh state every
# time), so the runtime is never exited and main() is called explicitly.
em++ $OPT_FLAGS -fwasm-exceptions /build/ffw/ffw.o -L"$FF/lib" $LIBS -o /out/ffw.mjs \
  -sMODULARIZE=1 -sEXPORT_ES6=1 -sEXPORT_NAME=createFFW \
  -sENVIRONMENT=web,worker,node \
  -sINVOKE_RUN=0 -sEXIT_RUNTIME=0 \
  -sALLOW_MEMORY_GROWTH=1 -sINITIAL_MEMORY=33554432 -sMAXIMUM_MEMORY=4294967296 \
  -sSTACK_SIZE=4194304 \
  -sFORCE_FILESYSTEM=1 -lworkerfs.js \
  -sEXPORTED_RUNTIME_METHODS=FS,WORKERFS,callMain,UTF8ToString \
  -sEXPORTED_FUNCTIONS=_main,_malloc,_free \
  -sDYNAMIC_EXECUTION=0 -sTEXTDECODER=2 -sASSERTIONS=0

# The browser worker mounts the user's file with WORKERFS (read on demand,
# never copied): make sure the build really contains and exports it.
grep -q 'WORKERFS' /out/ffw.mjs || { echo "WORKERFS missing from ffw.mjs"; exit 1; }

# Versions of everything inside the module, for the site's licence page.
{
  echo "{"
  echo "  \"ffmpeg\": \"$(cat $FF/share/ffmpeg-version.txt | tr -d '\n')\","
  echo "  \"emscripten\": \"$(emcc --version | head -1 | sed 's/.*) //; s/ (.*//')\","
  echo "  \"x264\": \"0.165.3222 b35605a\","
  echo "  \"libvpx\": \"$(pkg-config --modversion vpx)\","
  echo "  \"opus\": \"$(pkg-config --modversion opus)\","
  echo "  \"lame\": \"4.0\","
  echo "  \"dav1d\": \"$(pkg-config --modversion dav1d)\","
  echo "  \"zimg\": \"$(pkg-config --modversion zimg)\","
  echo "  \"zlib\": \"$(pkg-config --modversion zlib)\""
  echo "}"
} > /out/versions.json
cp "$FF/share/ffmpeg-configuration.txt" /out/ffmpeg-configuration.txt
ls -la /out
