#!/bin/bash
# The Digicam video converter build: FFmpeg 7.1.3 (LGPL v2.1+, same component list as
# the CamPort iOS app) compiled to WebAssembly, plus the derived step engine
# (web_converter.c, MIT-derived from FFmpeg doc/examples/transcode.c).
# This file is part of the corresponding source published at
# https://thedigicam.com/assets/video-converter/source/ (see ../LICENSES.txt).
#
# Usage: assets/video-converter/source/build.sh [all|ffmpeg|engine]   (default: all)
#   ffmpeg    extract the pristine FFmpeg 7.1.3 tarball, configure + make static wasm libs
#   engine    compile web_converter.c against those libs -> ../core/cvw.js + ../core/cvw.wasm
#   To relink with a modified FFmpeg: edit the extracted source in $CVW_BUILD_DIR, rerun
#   "make install" there, then "build.sh engine".
#
# Get FFmpeg: https://ffmpeg.org/releases/ffmpeg-7.1.3.tar.xz
#   SHA-256 in ffmpeg-source.txt. Pass its path with FFMPEG_TARBALL=...
#
# Build notes:
# - Toolchain: emsdk "latest" (verified with emcc 7.0.1) in ~/emsdk. emsdk needs
#   Python >= 3.10; macOS Xcode python is 3.9, so EMSDK_PYTHON points at Homebrew python.
#     git clone https://github.com/emscripten-core/emsdk ~/emsdk
#     EMSDK_PYTHON=/opt/homebrew/bin/python3.13 ~/emsdk/emsdk install latest && ... activate latest
# - Source: the pristine upstream ffmpeg-7.1.3.tar.xz (no patches), extracted fresh into
#   $CVW_BUILD_DIR. FFmpeg configure refuses
#   source paths with whitespace, so configure runs from build/ with a relative "src" link.
# - Component list: identical to CamPort Scripts/build-ffmpeg.sh, minus
#   videotoolbox / audiotoolbox / h264_videotoolbox (Apple-only) and minus pthreads
#   (single-threaded). Still --disable-gpl --disable-version3 --disable-nonfree.
#   The only encoder is FFmpeg's native "aac"; H.264 is encoded by the browser's
#   WebCodecs VideoEncoder in JS, and MP4 muxing is done in JS by mp4-muxer.
#   The mp4 muxer and the two bsfs stay enabled only to keep the component list
#   comparable with the iOS build; the web engine does not call them.
# - AC-3 patch (Scripts/patches/0001-aarch64-ac3-lgpl-c-fallback.patch): NOT applied.
#   It only removes the GPL aarch64 NEON AC-3 DSP objects and the ARCH_AARCH64 init
#   call. This build passes --arch=x86_32 (the usual emscripten trick, as ffmpeg.wasm
#   does) with --disable-asm; configure then reports ARCH_AARCH64=0 and ARCH_X86=0, so
#   neither aarch64 nor x86 DSP objects are built and AC-3 uses the plain LGPL C DSP
#   (only libavcodec/ac3dsp.o). ac3-patch-check.txt records the check.
# - All SIMD/asm paths are off; everything is portable C compiled with -O3 (no -msimd128).
# - components-diff-vs-ios.txt: the only CONFIG_ difference vs CamPort
#   Evidence/ffmpeg-components.h is CONFIG_H264_VIDEOTOOLBOX_ENCODER 1 -> 0
#   (videotoolbox/audiotoolbox are hwaccel/config.h switches, not components).
set -euo pipefail
here="$(cd "$(dirname "$0")" && pwd)"
TARBALL="${FFMPEG_TARBALL:-$here/ffmpeg-7.1.3.tar.xz}"
BUILD="${CVW_BUILD_DIR:-$HOME/.cache/thedigicam-cvw-build}"
PREFIX="$BUILD/prefix"
EVID="$here"
OUT="$here/../core"
which="${1:-all}"

if ! command -v emcc >/dev/null 2>&1; then
  export EMSDK_PYTHON="${EMSDK_PYTHON:-/opt/homebrew/bin/python3.13}"
  # shellcheck disable=SC1090
  source "${EMSDK:-$HOME/emsdk}/emsdk_env.sh" >/dev/null 2>&1
fi
command -v emcc >/dev/null || { echo "emcc not found (install emsdk)" >&2; exit 1; }

FFMPEG_FLAGS=(
  --prefix=../prefix --target-os=none --arch=x86_32 --enable-cross-compile
  --disable-asm --disable-inline-asm --disable-x86asm --disable-pthreads --disable-w32threads --disable-os2threads
  --disable-runtime-cpudetect --disable-stripping
  --cc=emcc --cxx=em++ --objcc=emcc --dep-cc=emcc --ar=emar --ranlib=emranlib --nm=emnm
  --extra-cflags=-O3
  --disable-gpl --disable-version3 --disable-nonfree --disable-autodetect --disable-everything --disable-programs --disable-doc
  --disable-debug --disable-network --disable-shared --enable-static
  --enable-avcodec --enable-avformat --enable-avfilter --enable-swresample --enable-swscale
  --enable-protocol=file --enable-demuxer=mpegts,mpegps,mpegvideo,h264,ac3,aac,avi,mov,dv,asf
  --enable-decoder=h264,mpeg2video,mpeg1video,mjpeg,mjpegb,dvvideo,h263,h263i,mpeg4,msmpeg4v1,msmpeg4v2,msmpeg4v3,wmv1,wmv2,wmv3,vc1,cinepak,msvideo1,ac3,aac,pcm_u8,pcm_s16le,pcm_s16be,pcm_mulaw,pcm_alaw,adpcm_ima_wav,adpcm_ima_qt,adpcm_ms,mp2,mp3,wmav1,wmav2,adpcm_g726,adpcm_g726le,amrnb
  --enable-parser=h264,mpegvideo,ac3,aac,mjpeg,h263,mpeg4video,mpegaudio,vc1 --enable-encoder=aac
  --enable-muxer=mp4 --enable-filter=buffer,buffersink,abuffer,abuffersink,idet,yadif,scale,format,aresample,aformat,null,anull,setsar
  --enable-bsf=aac_adtstoasc,h264_mp4toannexb
)

build_ffmpeg() {
  rm -rf "$BUILD"
  mkdir -p "$BUILD/obj" "$EVID"
  tar -xJf "$TARBALL" -C "$BUILD"
  ln -s ../ffmpeg-7.1.3 "$BUILD/obj/src"
  (
    cd "$BUILD/obj"
    printf '%q ' emconfigure src/configure "${FFMPEG_FLAGS[@]}" > "$EVID/configure-line.txt"
    echo >> "$EVID/configure-line.txt"
    emconfigure src/configure "${FFMPEG_FLAGS[@]}"
    emmake make -j"$(sysctl -n hw.ncpu 2>/dev/null || echo 4)"
    emmake make install
  )
  cp "$BUILD/obj/config_components.h" "$EVID/ffmpeg-components-wasm.h"
  # Component diff vs the iOS device build (expected: only videotoolbox/audiotoolbox lines).
  [ -n "${CAMPORT_COMPONENTS_H:-}" ] && diff <(grep '^#define CONFIG_' "$CAMPORT_COMPONENTS_H") \
       <(grep '^#define CONFIG_' "$BUILD/obj/config_components.h") \
       > "$EVID/components-diff-vs-ios.txt" || true
  {
    echo "License-relevant config.h lines (wasm build):"
    grep -E '^#define (CONFIG_GPL|CONFIG_VERSION3|CONFIG_NONFREE|ARCH_AARCH64|ARCH_X86|ARCH_X86_32|HAVE_X86ASM|HAVE_INLINE_ASM|HAVE_PTHREADS|HAVE_THREADS) ' "$BUILD/obj/config.h"
    echo
    echo "FFMPEG_LICENSE: $(grep FFMPEG_LICENSE "$BUILD/obj/config.h")"
    echo
    echo "AC-3 patch check: aarch64 objects present in build tree:"
    find "$BUILD/obj" -path '*aarch64*' -name '*.o' | sed 's#.*/obj/##' || true
    echo "(empty list above = the aarch64 GPL NEON AC-3 objects the iOS patch removes are never built here)"
    echo "AC-3 DSP objects built:"
    find "$BUILD/obj" -name '*ac3dsp*.o' | sed 's#.*/obj/##'
  } > "$EVID/ac3-patch-check.txt"
}

build_engine() {
  mkdir -p "$OUT"
  # Exported step API; see engine/web_converter.c.
  local exported='["_cvw_open","_cvw_step","_cvw_progress","_cvw_cancel","_cvw_close","_cvw_info_json","_cvw_last_error","_cvw_is_input_damage","_cvw_set_display_aspect","_cvw_set_compact_output","_cvw_set_max_width","_cvw_audio_config","_cvw_audio_config_size","_malloc","_free"]'
  emcc -O3 \
    -I"$PREFIX/include" "$here/web_converter.c" \
    -L"$PREFIX/lib" -lavfilter -lavformat -lavcodec -lswscale -lswresample -lavutil \
    -lworkerfs.js \
    -sMODULARIZE=1 -sEXPORT_NAME=createCvwModule -sENVIRONMENT=worker \
    -sALLOW_MEMORY_GROWTH=1 -sMAXIMUM_MEMORY=4GB -sINITIAL_MEMORY=64MB -sSTACK_SIZE=1MB \
    -sDYNAMIC_EXECUTION=0 -sFILESYSTEM=1 \
    -sEXPORTED_FUNCTIONS="$exported" \
    -sEXPORTED_RUNTIME_METHODS='["ccall","cwrap","UTF8ToString","stringToUTF8","FS","WORKERFS","HEAPU8"]' \
    -o "$OUT/cvw.js"
  ls -l "$OUT/cvw.js" "$OUT/cvw.wasm"
}

case "$which" in
  ffmpeg) build_ffmpeg ;;
  engine) build_engine ;;
  all) build_ffmpeg; build_engine ;;
  *) echo "usage: $0 [all|ffmpeg|engine]" >&2; exit 2 ;;
esac
