#!/bin/bash
#
# Builds the sound decoders of the Google Play version (-Pplay=true): FFmpeg configured under the
# LGPL 2.1 (no --enable-gpl, no --enable-version3, no --enable-nonfree), sound decoders only, as
# shared libraries, plus Media3's JNI wrapper (ffmpeg_jni.cc, Apache-2.0, copied unchanged from
# androidx/media 1.11.1 libraries/decoder_ffmpeg/src/main/jni). The results are committed in
# app/src/play/jniLibs/<abi>/, so an ordinary app build needs no NDK. Licence notes and the exact
# configure line: docs/LICENSES/ffmpeg-lgpl.md.
#
# Usage: tools/ffmpeg-lgpl/build.sh <Android NDK folder> [work folder]
# Works in Git Bash on Windows (uses the NDK's own make.exe) and on Linux or macOS.
# Tried with NDK r28c (28.2.13676358).
set -euo pipefail

FFMPEG_VERSION=6.1.6
FFMPEG_SHA256=d4fcb164028dd3beee5d92c0ac72e46aac6973c75ea12dc14de07bf8f407370a
FFMPEG_URL="https://ffmpeg.org/releases/ffmpeg-${FFMPEG_VERSION}.tar.xz"
API=26 # the app's minSdk

# AAC with LATM, MPEG audio layers 1-3, Dolby Digital (AC-3) and Digital Plus (E-AC-3), TrueHD/MLP,
# DTS, FLAC, ALAC, Opus, Vorbis, AMR and the telephone PCM kinds. Media3's FfmpegLibrary asks for
# these by name; mp1 and mp2 are the layer 1 and 2 decoders it reaches through "mp3".
DECODERS=(aac aac_latm mp1 mp2 mp3 ac3 eac3 truehd mlp dca flac alac opus vorbis amrnb amrwb pcm_alaw pcm_mulaw)

NDK="${1:?Give the Android NDK folder, e.g. \$LOCALAPPDATA/Android/Sdk/ndk/28.2.13676358}"
HERE="$(cd "$(dirname "$0")" && pwd)"
PROJECT="$(cd "$HERE/../.." && pwd)"
WORK="${2:-$PROJECT/.ffmpeg-build}"
case "$(uname -s)" in
  Linux) HOST=linux-x86_64; EXE= ;;
  Darwin) HOST=darwin-x86_64; EXE= ;;
  *) HOST=windows-x86_64; EXE=.exe ;;
esac
TC="$NDK/toolchains/llvm/prebuilt/$HOST/bin"
MAKE=make
if ! command -v make >/dev/null 2>&1; then MAKE="$NDK/prebuilt/$HOST/bin/make$EXE"; fi
[ -x "$TC/clang$EXE" ] || { echo "No clang in $TC"; exit 1; }

mkdir -p "$WORK/tmp"
WORK="$(cd "$WORK" && pwd)"
# configure's scratch files; Windows' own TEMP has backslashes Git Bash cannot use here.
export TMPDIR="$WORK/tmp"
cd "$WORK"
if [ ! -f "ffmpeg-$FFMPEG_VERSION.tar.xz" ]; then curl -fsSLo "ffmpeg-$FFMPEG_VERSION.tar.xz" "$FFMPEG_URL"; fi
echo "$FFMPEG_SHA256  ffmpeg-$FFMPEG_VERSION.tar.xz" | sha256sum -c -
# Paths make reads: on Windows the NDK's make.exe needs C:/... paths, not Git Bash's /c/... ones.
native() { if [ -n "$EXE" ]; then (cd "$1" && pwd -W); else (cd "$1" && pwd); fi; }

COMMON=(
  --target-os=android --enable-cross-compile
  --enable-shared --disable-static
  --disable-doc --disable-programs --disable-everything
  --disable-avdevice --disable-avformat --disable-swscale --disable-postproc --disable-avfilter
  --enable-avcodec --enable-avutil --enable-swresample
  --disable-network --disable-symver --disable-debug
  --disable-iconv --disable-zlib --disable-bzlib --disable-lzma --disable-v4l2-m2m --disable-vulkan
  --disable-autodetect --disable-mediacodec --disable-jni
  --cc="$TC/clang$EXE" --nm="$TC/llvm-nm$EXE" --ar="$TC/llvm-ar$EXE"
  --ranlib="$TC/llvm-ranlib$EXE" --strip="$TC/llvm-strip$EXE"
)
for d in "${DECODERS[@]}"; do COMMON+=(--enable-decoder="$d"); done

build_abi() {
  local abi=$1 triple=$2 arch=$3 cpu=$4 cflags=$5 ldflags=$6 asm=$7
  local out
  local target="--target=$triple$API"
  # 16 KB pages: Google Play requires it of 64-bit native code; harmless on 32-bit.
  local pages="-Wl,-z,max-page-size=16384"
  echo "=== FFmpeg $FFMPEG_VERSION for $abi"
  # Built inside a fresh copy of the source (configure would write Git Bash paths otherwise).
  rm -rf "$WORK/obj-$abi" "$WORK/out/$abi"
  mkdir -p "$WORK/obj-$abi" "$WORK/out/$abi"
  out="$(native "$WORK/out/$abi")"
  tar -xJf "$WORK/ffmpeg-$FFMPEG_VERSION.tar.xz" -C "$WORK/obj-$abi" --strip-components=1
  cd "$WORK/obj-$abi"
  ./configure --prefix="$out" --arch="$arch" --cpu="$cpu" $asm \
    --extra-cflags="$target $cflags" --extra-ldflags="$target $pages $ldflags" \
    "${COMMON[@]}" >configure.log
  grep -q "^License: LGPL version 2.1 or later" configure.log || { echo "Not LGPL 2.1:"; grep License configure.log; exit 1; }
  "$MAKE" -j"$(nproc 2>/dev/null || echo 4)" >make.log 2>&1 || { tail -30 make.log; exit 1; }
  "$MAKE" install-libs install-headers >>make.log 2>&1
  # Media3's JNI wrapper, linked against the shared libraries.
  "$TC/clang++$EXE" $target -std=c++11 -O2 -fPIC -shared -fvisibility=hidden -fvisibility-inlines-hidden \
    -I"$out/include" "$HERE/ffmpeg_jni.cc" -o "$out/lib/libffmpegJNI.so" \
    -L"$out/lib" -lswresample -lavcodec -lavutil -llog -landroid $pages -Wl,-Bsymbolic -static-libstdc++
  local dest="$PROJECT/app/src/play/jniLibs/$abi"
  rm -rf "$dest"
  mkdir -p "$dest"
  for lib in avutil swresample avcodec ffmpegJNI; do
    "$TC/llvm-strip$EXE" --strip-unneeded -o "$dest/lib$lib.so" "$out/lib/lib$lib.so"
  done
  cd "$WORK"
}

build_abi armeabi-v7a armv7a-linux-androideabi arm armv7-a "-march=armv7-a -mfloat-abi=softfp -mfpu=neon" "-Wl,--fix-cortex-a8" ""
build_abi arm64-v8a aarch64-linux-android aarch64 armv8-a "" "" ""
# The laptop's virtual TV and phone only: no assembler, as Media3's own script does.
build_abi x86 i686-linux-android x86 i686 "" "" --disable-asm
build_abi x86_64 x86_64-linux-android x86_64 x86-64 "" "" --disable-asm

grep "^License\|^External libraries\|^Enabled decoders" -A3 "$WORK/obj-arm64-v8a/configure.log" | head -20
ls -l "$PROJECT"/app/src/play/jniLibs/*/
