#!/usr/bin/env bash
# Prove Godot actually emits a transcoded movie's audio -- with no audio device.
#
#   tools/verify-video-audio ADV
#
# This container has no sound card and Godot falls back to the dummy driver, so
# "does it play" looked unanswerable from here. It is not: an AudioEffectRecord
# on the Master bus makes Godot write its own mixed output to a WAV from inside
# a headless run. That is Godot rendering audio to a file instead of a device --
# no new dependency, no image rebuild, and it tests the real playback path
# rather than the file the encoder produced.
#
# What this checks is that GODOT EMITS NON-SILENCE from the movie. It is
# deliberately NOT a fidelity comparison against the source: a difference-signal
# RMS between a transcode and its source is inconclusive without cross-
# correlation alignment and an agreed downmix -- a one-sample offset makes the
# residual nearly as loud as the signal. Level and non-silence are what this
# claims.
set -euo pipefail
cd "${PROJECT_DIR:-/work}"
name="${1:-ADV}"
OUT="${OUT:-${TMPDIR:-/tmp}/verify-video-audio}"
export DISPLAY="${DISPLAY:-:97}"
mkdir -p "$OUT"
[ -d port/.godot ] || godot --headless --path port --import >/dev/null 2>&1

wav="$OUT/$name.godot.wav"
rm -f "$wav"
cat > "$OUT/probe.gd" <<'GD'
extends SceneTree

func _init() -> void:
	var args := {}
	for a in OS.get_cmdline_user_args():
		if a.begins_with("--") and a.contains("="):
			var p := a.substr(2).split("=", true, 1)
			args[p[0]] = p[1]

	var tree_ := ExportTree.locate()
	if tree_.root == "":
		push_error(tree_.error); quit(2); return
	var v: Dictionary = tree_.video(args.get("video", "ADV"))
	if v.is_empty():
		push_error(tree_.error); quit(2); return

	# Record the MASTER bus: whatever Godot mixes, including the dummy driver's
	# output. This is the real playback path, not the encoded file.
	var rec := AudioEffectRecord.new()
	AudioServer.add_bus_effect(0, rec)

	var stream := VideoStreamTheora.new()
	stream.file = v["path"]
	var p := VideoStreamPlayer.new()
	p.stream = stream
	get_root().add_child(p)
	await process_frame
	rec.set_recording_active(true)
	p.play()
	var seconds := float(args.get("seconds", "6"))
	var t := 0.0
	while t < seconds and p.is_playing():
		await process_frame
		t += get_root().get_process_delta_time()
	rec.set_recording_active(false)
	var clip := rec.get_recording()
	if clip == null:
		push_error("no recording came back from the Master bus"); quit(3); return
	clip.save_to_wav(args.get("out", "/tmp/godot-audio.wav"))
	print("recorded %.2f s, %d Hz, stereo=%s -> %s" % [
		t, clip.mix_rate, clip.stereo, args.get("out", "")])
	quit(0)
GD

godot --path port --resolution 320x180 --script "$OUT/probe.gd" -- \
  "--video=$name" "--out=$wav" "--seconds=${SECONDS_TO_RECORD:-6}" 2>&1 \
  | grep -viE "ALSA|Vulkan|V-Sync|OpenGL|audio driver|^ *at: |Condition|^$" || true

[ -s "$wav" ] || { echo "verify-video-audio: Godot wrote no WAV" >&2; exit 1; }
echo "--- what Godot emitted ---"
ffmpeg -hide_banner -i "$wav" -af volumedetect -f null - 2>&1 \
  | grep -oE "(max_volume|mean_volume): [-0-9.]+ dB" | sed 's/^/  /'
mean=$(ffmpeg -hide_banner -i "$wav" -af volumedetect -f null - 2>&1 \
  | grep -oE "mean_volume: [-0-9.]+" | grep -oE -- "-?[0-9.]+")
# Digital silence reports around -91 dB at 16-bit. Anything near that is nothing.
awk -v m="$mean" 'BEGIN{ if (m < -80) { print "  VERDICT: silence -- Godot is not emitting this movie\047s audio"; exit 1 }
                         else { printf "  VERDICT: audio present (mean %.1f dB)\n", m } }'
