#!/bin/sh
# Builds the LGPL media libraries for OMNIvour for Windows: FFmpeg + LAME as separate, replaceable
# shared libraries (avcodec, avformat, avutil, avfilter, swscale, swresample, libmp3lame) plus the
# ffmpeg.exe and ffprobe.exe helpers, for win-x64 and win-arm64, cross-compiled with the pinned
# llvm-mingw release (UCRT) inside the pinned Debian container. H.264, HEVC and AAC are encoded by
# Windows Media Foundation; no GPL, nonfree or version 3 code. Output: dist/ (gitignored).
# Then: dist/MANIFEST.json (copy to MANIFEST.json when bumping a version on purpose).
#
# Run from the repository root on any Docker host (see README.md):
#   docker run --rm -v "$PWD:/src" -w /src/apps/windows/ffmpeg <CONTAINER_IMAGE> sh -c 'sh prepare.sh && sh build.sh'
set -eu
HERE=$(cd "$(dirname "$0")" && pwd)
REPO=$(cd "$HERE/../../.." && pwd)
. "$HERE/versions.env"
DIST="$HERE/dist"
# One fixed, neutral work path for both passes: FFmpeg embeds its full configure line (prefix,
# data dir, include and library paths) in every library, so the two passes are byte-identical
# only at the same absolute path. -ffile-prefix-map maps it again for source paths, the link
# strips debug info (-Wl,-s: llvm-mingw's CRT startup objects carry the toolchain's own build
# paths) and writes no timestamp.
ROOT=/omnivour-ffmpeg-build
DL=/tmp/omnivour-ffmpeg-dl
PASS1=/tmp/omnivour-ffmpeg-pass1
rm -rf "$ROOT" "$DL" "$PASS1" && mkdir -p "$ROOT" "$DL" "$PASS1"
trap 'rm -rf "$ROOT" "$DL" "$PASS1"' EXIT
export SOURCE_DATE_EPOCH=0
JOBS=$(nproc)
log() { printf '== %s\n' "$*"; }

log "download into $DL"
cd "$DL"
curl -sSfL -o ffmpeg.tar.xz "$FFMPEG_URL"
curl -sSfL -o lame.tar.gz "$LAME_URL"
curl -sSfL -o llvm-mingw.tar.xz "$LLVM_MINGW_URL"
printf '%s  ffmpeg.tar.xz\n%s  lame.tar.gz\n%s  llvm-mingw.tar.xz\n' \
    "$FFMPEG_SHA256" "$LAME_SHA256" "$LLVM_MINGW_SHA256" | sha256sum -c -

log "llvm-mingw $LLVM_MINGW_TAG"
mkdir -p "$DL/toolchain"
tar xJf llvm-mingw.tar.xz -C "$DL/toolchain" --strip-components 1
PATH="$DL/toolchain/bin:$PATH"
export PATH
clang --version | head -1

# The licences as FFmpeg and LAME ship them: the manifest only names them after both compare equal.
mkdir -p "$DL/check/ffmpeg" "$DL/check/lame"
tar xJf ffmpeg.tar.xz -C "$DL/check/ffmpeg" --strip-components 1
tar xzf lame.tar.gz -C "$DL/check/lame" --strip-components 1
cmp "$DL/check/ffmpeg/COPYING.LGPLv2.1" "$REPO/licenses/LGPL-2.1.txt" \
    || { echo "FAIL: licenses/LGPL-2.1.txt differs from FFmpeg's COPYING.LGPLv2.1"; exit 1; }
cmp "$DL/check/lame/COPYING" "$REPO/licenses/LGPL-2.0.txt" \
    || { echo "FAIL: licenses/LGPL-2.0.txt differs from LAME's COPYING"; exit 1; }
rm -rf "$DL/check"

# LAME 4.0's configure insists on pkg-config even with its frontend disabled. A stand-in that
# finds no optional libraries keeps the build free of extra tools (as on the Mac).
mkdir -p "$DL/bin"
cat >"$DL/bin/pkg-config" <<'SHIM'
#!/bin/sh
case "$1" in --version) echo 0.29.2 ;; --atleast-pkgconfig-version) exit 0 ;; *) exit 1 ;; esac
SHIM
chmod +x "$DL/bin/pkg-config"
PATH="$DL/bin:$PATH"

# FFmpeg's one host program, ffbuild/bin2c, embeds fftools/resources (graph.html, graph.css) as C
# arrays. The container has no native C compiler, so this stand-in writes exactly what
# ffbuild/bin2c.c writes (same symbol names, bytes and trailing 0x00) and make runs it as BIN2C.
cat >"$DL/bin/ffmpeg-bin2c" <<'SHIM'
#!/usr/bin/env python3
import sys
src, dst, name = sys.argv[1], sys.argv[2], sys.argv[3]
data = open(src, "rb").read()
with open(dst, "w", newline="\n") as out:
    out.write("const unsigned char ff_%s_data[] = { " % name)
    out.write("".join("0x%02x, " % b for b in data))
    out.write("0x00 };\n")
    out.write("const unsigned int ff_%s_len = %u;\n" % (name, len(data)))
SHIM
chmod +x "$DL/bin/ffmpeg-bin2c"

LDF="-Wl,-s -Wl,--no-insert-timestamp -Wl,--dynamicbase -Wl,--nxcompat -Wl,--high-entropy-va"

# One build of LAME then FFmpeg for one architecture, from fresh source trees under $ROOT.
build_pass() {
    triple=$1 arch=$2
    rm -rf "$ROOT" && mkdir -p "$ROOT/lame-src" "$ROOT/ffmpeg-src"
    tar xzf "$DL/lame.tar.gz" -C "$ROOT/lame-src" --strip-components 1
    tar xJf "$DL/ffmpeg.tar.xz" -C "$ROOT/ffmpeg-src" --strip-components 1
    (
        cd "$ROOT/lame-src"
        CC="$triple-clang" CFLAGS="-O2 -ffile-prefix-map=$ROOT=/omnivour-ffmpeg" LDFLAGS="$LDF" \
            ./configure --host="$triple" --prefix="$ROOT/out/lame" \
            --enable-shared --disable-static --disable-frontend --disable-decoder --disable-gtktest \
            >"$ROOT/lame.log" 2>&1
        make -j"$JOBS" >>"$ROOT/lame.log" 2>&1 && make install >>"$ROOT/lame.log" 2>&1
    ) || { tail -40 "$ROOT/lame.log"; exit 1; }
    ASM=""
    [ "$arch" = x86_64 ] && ASM="--x86asmexe=nasm"
    (
        cd "$ROOT/ffmpeg-src"
        # mfenc.c (the Media Foundation encoders) does not compile without D3D11VA in FFmpeg 8.1.3,
        # so --enable-d3d11va is on: it builds only the D3D11 hardware context (no hwaccel is
        # enabled under --disable-everything), and the manifest records the resulting imports.
        # The container has no native C compiler. configure only compile-checks the host compiler
        # for C11, and the only host program this configuration runs is bin2c (replaced by the
        # stand-in above; no hardcoded tables), so the target clang stands in. Any other host
        # program that had to run would fail the build loudly.
        # shellcheck disable=SC2086
        ./configure --prefix="$ROOT/out/ffmpeg" --datadir="$ROOT/share" --arch="$arch" --target-os=mingw32 \
            --enable-cross-compile --cross-prefix="$triple-" --cc="$triple-clang" --host-cc="$triple-clang" $ASM \
            --extra-cflags="-I$ROOT/out/lame/include -ffile-prefix-map=$ROOT=/omnivour-ffmpeg" \
            --extra-ldflags="-L$ROOT/out/lame/lib -Wl,-s -Wl,--no-insert-timestamp -Wl,--dynamicbase -Wl,--nxcompat -Wl,--high-entropy-va" \
            --disable-gpl --disable-nonfree --disable-version3 \
            --enable-shared --disable-static \
            --disable-autodetect --enable-mediafoundation --enable-d3d11va --enable-libmp3lame \
            --disable-pthreads --enable-w32threads \
            --disable-network --disable-avdevice --disable-doc --disable-debug --disable-ffplay \
            --disable-everything \
            --enable-protocol=file,pipe \
            --enable-demuxer=mov,matroska,avi,mp3,wav,flac,aac,ogg,asf,aiff \
            --enable-muxer=mp4,mov,matroska,avi,gif,mp3,wav,flac,adts,ipod,asf,aiff \
            --enable-decoder=h264,hevc,vp8,vp9,mpeg4,msmpeg4v3,mjpeg,prores,vc1,wmv3,rawvideo,aac,mp3float,flac,vorbis,opus,alac,wmav2,wmapro,ac3,eac3,pcm_s16le,pcm_s16be,pcm_s24le,pcm_s24be,pcm_s32le,pcm_f32le,pcm_u8,pcm_alaw,pcm_mulaw \
            --enable-encoder=h264_mf,hevc_mf,aac_mf,libmp3lame,flac,gif,wmav2,pcm_s16le,pcm_s16be \
            --enable-parser=h264,hevc,aac,mpegaudio,flac,vorbis,opus,vp8,vp9,mpeg4video \
            --enable-bsf=aac_adtstoasc,h264_mp4toannexb,hevc_mp4toannexb,extract_extradata \
            --enable-filter=scale,fps,split,palettegen,paletteuse,format,aresample,aformat,anull,null,setsar,setpts,asetpts \
            --enable-ffmpeg --enable-ffprobe >"$ROOT/ffmpeg.log" 2>&1
        make -j"$JOBS" BIN2C="$DL/bin/ffmpeg-bin2c" >>"$ROOT/ffmpeg.log" 2>&1 \
            && make install BIN2C="$DL/bin/ffmpeg-bin2c" >>"$ROOT/ffmpeg.log" 2>&1
    ) || { grep -E " error: " "$ROOT/ffmpeg.log" | head -20; tail -40 "$ROOT/ffmpeg.log"; exit 1; }
}

# The nine shipped files of the current pass, one per line (absolute paths).
pass_files() {
    { find "$ROOT/out/ffmpeg/bin" -maxdepth 1 -type f \( -name '*.dll' -o -name '*.exe' \)
      find "$ROOT/out/lame/bin" -maxdepth 1 -type f -name '*.dll'; } | LC_ALL=C sort
}

# Static checks on the generated configuration of the current pass.
check_config() {
    rid=$1
    python3 - "$ROOT/ffmpeg-src" "$rid" "$DL/license-$rid" <<'PY'
import os, re, sys
src, rid, license_out = sys.argv[1], sys.argv[2], sys.argv[3]
def die(msg):
    print("FAIL: %s: %s" % (rid, msg)); sys.exit(1)
config = open(os.path.join(src, "config.h"), encoding="utf-8").read()
components = open(os.path.join(src, "config_components.h"), encoding="utf-8").read()
# The manifest licence is FFmpeg's own statement, mapped to SPDX; anything else stops the build.
stated = re.findall(r'^#define FFMPEG_LICENSE "([^"]*)"$', config, re.M)
spdx = {"LGPL version 2.1 or later": "LGPL-2.1-or-later"}
if len(stated) != 1 or stated[0] not in spdx:
    die("config.h FFMPEG_LICENSE is %s, not LGPL version 2.1 or later" % stated)
for name in ("CONFIG_GPL", "CONFIG_NONFREE", "CONFIG_VERSION3", "CONFIG_NETWORK"):
    if not re.search(r"^#define %s 0$" % name, config, re.M):
        die("config.h does not set %s 0" % name)
for name in ("LIBX264", "LIBX265", "LIBFDK_AAC", "LIBVPX", "LIBVORBIS", "LIBOPUS"):
    if re.search(r"^#define CONFIG_%s 1$" % name, config, re.M):
        die("config.h enables CONFIG_%s" % name)
def enabled(kind):
    return sorted(m.lower() for m in re.findall(r"^#define CONFIG_(\w+)_%s 1$" % kind, components, re.M))
# Every component kind, exactly: the configure lists plus what FFmpeg itself pulls in (h263 for
# mpeg4, the ac3 parser, the vp9 and pgs bitstream filters, the trim/crop/flip/rotate filters
# ffmpeg.exe's autorotate and trimming use). The ffmpeg gate pins these lines.
want = {
    "PROTOCOL": "file pipe".split(),
    "DEMUXER": "aac aiff asf avi flac matroska mov mp3 ogg wav".split(),
    "MUXER": "adts aiff asf avi flac gif ipod matroska mov mp3 mp4 wav".split(),
    "DECODER": "aac ac3 alac eac3 flac h263 h264 hevc mjpeg mp3float mpeg4 msmpeg4v3 opus pcm_alaw pcm_f32le pcm_mulaw pcm_s16be pcm_s16le pcm_s24be pcm_s24le pcm_s32le pcm_u8 prores rawvideo vc1 vorbis vp8 vp9 wmapro wmav2 wmv3".split(),
    "ENCODER": "aac_mf flac gif h264_mf hevc_mf libmp3lame pcm_s16be pcm_s16le wmav2".split(),
    "PARSER": "aac ac3 flac h264 hevc mpeg4video mpegaudio opus vorbis vp8 vp9".split(),
    "BSF": "aac_adtstoasc extract_extradata h264_mp4toannexb hevc_mp4toannexb pgs_frame_merge vp9_superframe vp9_superframe_split".split(),
    "FILTER": "aformat anull aresample asetpts atrim crop format fps hflip null palettegen paletteuse rotate scale setpts setsar split transpose trim vflip".split(),
    "HWACCEL": "".split(),
    "INDEV": "".split(),
    "OUTDEV": "".split(),
}
for kind, names in want.items():
    got = enabled(kind)
    if got != sorted(names):
        die("config_components.h %ss are %s, expected %s" % (kind.lower(), got, sorted(names)))
for name in ("webm", "ogg", "opus", "oga"):
    if name in enabled("MUXER"):
        die("config_components.h enables the %s muxer" % name)
with open(license_out, "w") as out:
    out.write(spdx[stated[0]] + "\n")
print("config: %s; exact protocols, demuxers, muxers, decoders, encoders, parsers, bsfs, filters; no hwaccel or device" % spdx[stated[0]])
PY
}

rm -rf "$DIST" && mkdir -p "$DIST"
for spec in x86_64-w64-mingw32:win-x64:x86_64 aarch64-w64-mingw32:win-arm64:aarch64; do
    TRIPLE=${spec%%:*}
    rest=${spec#*:}
    RID=${rest%%:*}
    ARCH=${rest#*:}
    log "LAME $LAME_VERSION + FFmpeg $FFMPEG_VERSION ($RID, pass 1 of 2)"
    build_pass "$TRIPLE" "$ARCH"
    check_config "$RID"
    mkdir -p "$PASS1/$RID"
    for f in $(pass_files); do cp "$f" "$PASS1/$RID/"; done
    log "LAME $LAME_VERSION + FFmpeg $FFMPEG_VERSION ($RID, pass 2 of 2, same path)"
    build_pass "$TRIPLE" "$ARCH"
    check_config "$RID"
    mkdir -p "$DIST/$RID"
    n=0
    for f in $(pass_files); do
        file=$(basename "$f")
        [ -f "$PASS1/$RID/$file" ] || { echo "FAIL: $RID/$file is missing from pass 1"; exit 1; }
        cmp "$PASS1/$RID/$file" "$f" || { echo "FAIL: build is not reproducible ($RID/$file differs between passes)"; exit 1; }
        cp "$f" "$DIST/$RID/$file"
        n=$((n + 1))
    done
    [ "$n" -eq 9 ] || { echo "FAIL: $RID build produced $n files, expected 9"; ls "$DIST/$RID"; exit 1; }
    [ "$(ls "$PASS1/$RID" | wc -l)" -eq 9 ] || { echo "FAIL: $RID pass 1 produced a different file set"; exit 1; }
done
rm -rf "$ROOT"

log "self-checks"
for f in "$DIST"/win-*/*; do
    RID=$(basename "$(dirname "$f")")
    NAME=$(basename "$f")
    HEAD=$(llvm-readobj --file-headers "$f")
    case "$RID" in
        win-x64) MACHINE=IMAGE_FILE_MACHINE_AMD64 ;;
        win-arm64) MACHINE=IMAGE_FILE_MACHINE_ARM64 ;;
    esac
    printf '%s\n' "$HEAD" | grep -q "Machine: $MACHINE" || { echo "FAIL: $RID/$NAME is not $MACHINE"; exit 1; }
    for flag in DYNAMIC_BASE NX_COMPAT HIGH_ENTROPY_VA; do
        printf '%s\n' "$HEAD" | grep -q "IMAGE_DLL_CHARACTERISTICS_$flag" || { echo "FAIL: $RID/$NAME lacks $flag"; exit 1; }
    done
    printf '%s\n' "$HEAD" | grep -q "TimeDateStamp: 1970-01-01 00:00:00 (0x0)" || { echo "FAIL: $RID/$NAME carries a link timestamp"; exit 1; }
    IMPORTS=$(llvm-readobj --coff-imports "$f" | sed -n 's/^ *Name: //p' | sort -u)
    for imp in $IMPORTS; do
        lower=$(printf '%s' "$imp" | tr 'A-Z' 'a-z')
        case "$lower" in
            ws2_32.dll|wsock32.dll|mswsock.dll|wininet.dll|winhttp.dll|urlmon.dll|secur32.dll|crypt32.dll|iphlpapi.dll|dnsapi.dll|netapi32.dll|libwinpthread-1.dll)
                echo "FAIL: $RID/$NAME imports $imp (network, TLS or pthreads)"; exit 1 ;;
        esac
    done
    # The one allowed hit is FFmpeg's own temp-file template in libavutil/file_open.c
    # ("/tmp/%sXXXXXX", a runtime fallback string), not a build path.
    LEAK=$(grep -a -o -E '(/tmp/|/home/|/root/|/src/apps/|omnivour-ffmpeg-dl|omnivour-ffmpeg-pass1)[ -~]{0,40}' "$f" \
        | grep -v -x -F '/tmp/%sXXXXXX' | head -1 || true)
    [ -z "$LEAK" ] || { echo "FAIL: $RID/$NAME embeds a build path ($LEAK)"; exit 1; }
    if [ "$NAME" = ffmpeg.exe ]; then
        # ffmpeg -L prints the notice line-wrapped ("...GNU Lesser General Public" / "License as
        # published..."), so the two fragments are checked separately (verify.sh checks the text).
        grep -a -q "the terms of the GNU Lesser General Public" "$f" \
            && grep -a -q "version 2.1 of the License, or (at your option) any later version" "$f" \
            || { echo "FAIL: $RID/ffmpeg.exe does not carry the LGPL 2.1 notice"; exit 1; }
    fi
done
# The licence as FFmpeg's own configuration states it (config.h FFMPEG_LICENSE, every pass).
cmp "$DL/license-win-x64" "$DL/license-win-arm64" || { echo "FAIL: the architectures state different licences"; exit 1; }
LICENSE_ID=$(cat "$DL/license-win-x64")
export LICENSE_ID

log "manifest"
python3 - "$DIST" "$HERE" <<'PY'
import hashlib, json, os, subprocess, sys
dist, here = sys.argv[1], sys.argv[2]
env = dict(l.strip().split("=", 1) for l in open(os.path.join(here, "versions.env")) if "=" in l and not l.startswith("#"))
machines = {"win-x64": "AMD64", "win-arm64": "ARM64"}
files = {}
for rid in sorted(machines):
    for name in sorted(os.listdir(os.path.join(dist, rid))):
        path = os.path.join(dist, rid, name)
        data = open(path, "rb").read()
        out = subprocess.run(["llvm-readobj", "--coff-imports", path], capture_output=True, text=True, check=True).stdout
        imports = sorted({l.split(":", 1)[1].strip() for l in out.split("\n") if l.strip().startswith("Name:")})
        files[f"{rid}/{name}"] = {
            "sha256": hashlib.sha256(data).hexdigest(),
            "bytes": len(data),
            "machine": machines[rid],
            "imports": imports,
        }
manifest = {
    "license": os.environ["LICENSE_ID"],
    "notices": ["licenses/LGPL-2.1.txt", "licenses/LGPL-2.0.txt"],
    "ffmpeg_version": env["FFMPEG_VERSION"], "ffmpeg_sha256": env["FFMPEG_SHA256"],
    "lame_version": env["LAME_VERSION"], "lame_sha256": env["LAME_SHA256"],
    "lgpl_components": [f"FFmpeg {env['FFMPEG_VERSION']}", f"LAME {env['LAME_VERSION']}"],
    "built_with": "llvm-mingw " + env["LLVM_MINGW_TAG"] + " (ucrt)",
    "llvm_mingw_sha256": env["LLVM_MINGW_SHA256"],
    "container_image": env["CONTAINER_IMAGE"],
    "apt_packages": {"make": env["APT_MAKE"], "nasm": env["APT_NASM"], "python3": env["APT_PYTHON3"]},
    "runtime_verified": [],
    "total_bytes": sum(f["bytes"] for f in files.values()),
    "files": files,
}
with open(os.path.join(dist, "MANIFEST.json"), "w", newline="\n") as out:
    json.dump(manifest, out, indent=2, sort_keys=True)
    out.write("\n")
print("total MB:", round(manifest["total_bytes"] / 1e6, 1))
PY
log "done: $DIST"
