#!/bin/sh
# Builds DropBridgeCloud's AVI reader (safari/media/vendor/ffmpeg-avi/) from
# FFmpeg's source, inside Docker with Emscripten.
#
# The build is LGPL-2.1-or-later only: no --enable-gpl, no --enable-nonfree.
# It contains only the AVI reader (with DV-in-AVI) and the decoders for formats commonly found
# in AVI files whose patents have expired (MPEG-4 Part 2 / DivX / Xvid,
# Windows MPEG-4, H.263, MJPEG, MPEG-1/2, DV, MP3, MP2, AC-3, PCM, ADPCM).
# H.264 and AAC are left out on purpose: their patents are still active.
#
# Usage: sh website/oss/ffmpeg-avi/build.sh  (needs git and Docker)
set -eu

FFMPEG_TAG=n7.1.1
EMSDK_IMAGE=emscripten/emsdk:3.1.74

here=$(cd "$(dirname "$0")" && pwd)
root=$(cd "$here/../../.." && pwd)
out="$root/safari/media/vendor/ffmpeg-avi"
work=${WORK:-$(mktemp -d)}

[ -d "$work/ffmpeg" ] || git clone -q --depth 1 -b "$FFMPEG_TAG" https://github.com/FFmpeg/FFmpeg.git "$work/ffmpeg"
cp "$here/avi_reader.c" "$work/"

docker run --rm -v "$work:/work" -w /work/ffmpeg "$EMSDK_IMAGE" sh -euc '
  if [ ! -f /work/prefix/lib/libavformat.a ]; then
    emconfigure ./configure \
      --prefix=/work/prefix --target-os=none --arch=x86_32 --enable-cross-compile \
      --cc=emcc --cxx=em++ --ar=emar --ranlib=emranlib --nm=emnm \
      --disable-asm --disable-x86asm --disable-inline-asm --disable-stripping \
      --disable-programs --disable-doc --disable-debug --disable-runtime-cpudetect \
      --disable-autodetect --disable-network --disable-pthreads --disable-w32threads --disable-os2threads \
      --disable-avdevice --disable-avfilter \
      --disable-everything \
      --enable-protocol=file --enable-demuxer=avi,dv \
      --enable-decoder=mpeg4,msmpeg4v1,msmpeg4v2,msmpeg4v3,h263,mjpeg,mpeg1video,mpeg2video,dvvideo,rawvideo,cinepak,msvideo1 \
      --enable-decoder=mp3float,mp2float,ac3,pcm_s16le,pcm_u8,pcm_s24le,adpcm_ms,adpcm_ima_wav \
      --enable-parser=mpeg4video,h263,mjpeg,mpegvideo,mpegaudio,ac3 \
      --extra-cflags="-O3" >/dev/null
    emmake make -j"$(nproc)" >/dev/null
    emmake make install >/dev/null
  fi
  cd /work
  emcc -O3 avi_reader.c -I/work/prefix/include -L/work/prefix/lib \
    -lavformat -lavcodec -lswscale -lswresample -lavutil -lworkerfs.js \
    -sMODULARIZE=1 -sEXPORT_ES6=1 -sENVIRONMENT=worker -sDYNAMIC_EXECUTION=0 \
    -sALLOW_MEMORY_GROWTH=1 -sINITIAL_MEMORY=64MB -sMAXIMUM_MEMORY=2GB -sFILESYSTEM=1 \
    -sEXPORTED_FUNCTIONS=_fp_open,_fp_info,_fp_start,_fp_next,_fp_video,_fp_audio,_fp_audio_frames,_fp_ts,_fp_close \
    -sEXPORTED_RUNTIME_METHODS=ccall,FS,WORKERFS,HEAPU8,HEAPF32,HEAPF64 \
    -o avi_reader.mjs
'

mkdir -p "$out"
# Renamed to .js so Safari serves it as a JavaScript module.
cp "$work/avi_reader.mjs" "$out/avi_reader.js"
cp "$work/avi_reader.wasm" "$out/"
cp "$work/ffmpeg/COPYING.LGPLv2.1" "$out/COPYING.LGPLv2.1"
echo "Built $out"
ls -la "$out"
