#!/bin/sh
# Rebuilds the AAC encoder used by the export on iPhone (the WASM inside app/vendor/mediabunny-aac-encoder.min.mjs)
# from a pinned FFmpeg release, so the exact source of what we ship is known and can be handed out (LGPL).
# Same configure and link flags as @mediabunny/aac-encoder 1.61.5 (upstream/README.md), only the FFmpeg
# source is the signed release tarball instead of an unpinned git checkout.
#
# The FFmpeg tarball is the one published next to the app (app/source/, signature .asc beside it). The toolchain
# is not committed (see .gitignore): _toolchain/emsdk-<EMSDK_VERSION>, with that SDK and mingw-7.1.0-64bit (for
# make) installed by emsdk. Run from Git Bash: sh tools/aac-encoder-build/build.sh
# Output: aac.js here (Emscripten glue + inlined WASM); scripts/vendor.mjs puts it into the vendored bundle.
set -eu

FFMPEG_VERSION=8.1.3
FFMPEG_SHA256=7138d28c96d9d3e3af4ee3d8cad72741f8ffb40da90c1112235dea3ecd3178a3
EMSDK_VERSION=6.0.13

HERE=$(cd "$(dirname "$0")" && pwd)
EMSDK="$HERE/_toolchain/emsdk-$EMSDK_VERSION"
WORK="$HERE/_work"
SRC="$WORK/ffmpeg-$FFMPEG_VERSION"
# (app/source/ in this repository; set FFMPEG_TARBALL when building from the copy published with the app)
TARBALL="${FFMPEG_TARBALL:-$HERE/../../app/source/ffmpeg-$FFMPEG_VERSION.tar.xz}"

echo "$FFMPEG_SHA256 *$TARBALL" | sha256sum -c -

export EMSDK_PYTHON="$EMSDK/python/3.13.3_64bit/python.exe"
export PATH="$EMSDK/upstream/emscripten:$EMSDK/node/24.19.0_64bit/bin:$EMSDK/mingw/7.1.0_64bit/bin:$PATH"
emcc --version | head -1

# a fresh copy of the release every time (configure and make write into the tree)
rm -rf "$SRC"
mkdir -p "$WORK"
"$EMSDK_PYTHON" -I -c "import sys,tarfile; tarfile.open(sys.argv[1]).extractall(sys.argv[2], filter='data')" "$TARBALL" "$WORK"

mkdir -p "$WORK/tmp"
export TMPDIR="$WORK/tmp"
cd "$SRC"
./configure \
	--target-os=none \
	--arch=x86_32 \
	--enable-cross-compile \
	--disable-asm \
	--disable-x86asm \
	--disable-inline-asm \
	--disable-programs \
	--disable-doc \
	--disable-debug \
	--disable-all \
	--disable-everything \
	--disable-autodetect \
	--disable-pthreads \
	--disable-runtime-cpudetect \
	--enable-avcodec \
	--enable-encoder=aac \
	--cc=emcc \
	--cxx=em++ \
	--ar=emar \
	--ranlib=emranlib \
	--extra-cflags="-DNDEBUG -Oz -flto -msimd128" \
	--extra-ldflags="-Oz -flto"
mingw32-make -j"$(nproc)" SHELL=sh libavcodec/libavcodec.a libavutil/libavutil.a

cd "$HERE"
emcc upstream/bridge.c \
	"$SRC/libavcodec/libavcodec.a" \
	"$SRC/libavutil/libavutil.a" \
	-I"$SRC" \
	-s MODULARIZE=1 \
	-s EXPORT_ES6=1 \
	-s SINGLE_FILE=1 \
	-s ALLOW_MEMORY_GROWTH=1 \
	-s ENVIRONMENT=web,worker \
	-s FILESYSTEM=0 \
	-s MALLOC=emmalloc \
	-s SUPPORT_LONGJMP=0 \
	-s EXPORTED_RUNTIME_METHODS=cwrap,HEAPU8 \
	-s EXPORTED_FUNCTIONS=_malloc,_free \
	-msimd128 \
	-flto \
	-Oz \
	-o "$HERE/aac.js"
sha256sum "$HERE/aac.js"
