#!/bin/sh
# autopkgtest: load the LV2 plugin of the rncbc.org "v1" synthesizer
# family (drumkv1, samplv1, synthv1, padthv1) in a real (minimal) LV2
# host and verify that it
#
#   1. can be instantiated with the features it requires
#      (urid:map, worker:schedule),
#   2. restores its preset/state or accepts a patch:Set sample
#      (drumkv1/samplv1 need a sample, synthv1/padthv1 are pure
#      synthesizers),
#   3. renders non-silent audio for a MIDI note-on,
#   4. handles the note-off without producing NaN/Inf samples.
#
# The helper host (lv2_probe.c) lives in this directory and is compiled
# against the installed lilv/lv2 headers at test time.
#
# AI assisted code, reviewed and tested by snd@debian.org

set -eu

TESTDIR=$(cd "$(dirname "$0")" && pwd)
. "$TESTDIR/common.sh"

detect_app
NOTE=${RNCBC_NOTE:-$DEF_NOTE}
RUN_SECONDS=${RNCBC_LV2_SECONDS:-4}
MIN_PEAK=${RNCBC_MIN_PEAK:-0.001}

setup_env
trap cleanup EXIT
trap "cleanup; exit 130" INT
trap "cleanup; exit 143" TERM

# The plugin links against Qt, but never needs a display: force the
# offscreen platform plugin so the test also works on a bare testbed.
export QT_QPA_PLATFORM=offscreen

log "building the LV2 host helper"
PROBE="$WORKDIR/lv2_probe"
cc -O2 -o "$PROBE" "$TESTDIR/lv2_probe.c" \
	$(pkgconf --cflags --libs lilv-0 lv2) -lm \
	|| fail "cannot build lv2_probe"

"$PROBE" make-wav "$WORKDIR/sample.wav" \
	|| fail "cannot generate the test sample"

EXTRA_ARGS=
case $APP in
drumkv1)
	write_drumkv1_state "$WORKDIR/sample.wav" "$NOTE" \
		"$WORKDIR/state.xml"
	EXTRA_ARGS="--state $WORKDIR/state.xml"
	;;
samplv1)
	EXTRA_ARGS="--set-path http://samplv1.sourceforge.net/lv2#P101_SAMPLE_FILE $WORKDIR/sample.wav"
	;;
esac

log "instantiating and rendering MIDI note $NOTE through the LV2 plugin"
# shellcheck disable=SC2086
"$PROBE" --plugin-uri "$LV2_URI" --note "$NOTE" \
	--seconds "$RUN_SECONDS" --min-peak "$MIN_PEAK" \
	$EXTRA_ARGS \
	|| fail "LV2 plugin $LV2_URI did not render any audio"

log "PASS: LV2 plugin ${APP} instantiated and rendered audio"
