#! /usr/bin/bash

# (C) 2022-2023 IVAS codec Public Collaboration with portions copyright Dolby International AB, Ericsson AB,
# Fraunhofer-Gesellschaft zur Foerderung der angewandten Forschung e.V., Huawei Technologies Co. LTD.,
# Koninklijke Philips N.V., Nippon Telegraph and Telephone Corporation, Nokia Technologies Oy, Orange,
# Panasonic Holdings Corporation, Qualcomm Technologies, Inc., VoiceAge Corporation, and other
# contributors to this repository. All Rights Reserved.

# This software is protected by copyright law and by international treaties.
# The IVAS codec Public Collaboration consisting of Dolby International AB, Ericsson AB,
# Fraunhofer-Gesellschaft zur Foerderung der angewandten Forschung e.V., Huawei Technologies Co. LTD.,
# Koninklijke Philips N.V., Nippon Telegraph and Telephone Corporation, Nokia Technologies Oy, Orange,
# Panasonic Holdings Corporation, Qualcomm Technologies, Inc., VoiceAge Corporation, and other
# contributors to this repository retain full ownership rights in their respective contributions in
# the software. This notice grants no license of any kind, including but not limited to patent
# license, nor is any license granted by implication, estoppel or otherwise.

# Contributors are required to enter into the IVAS codec Public Collaboration agreement before making
# contributions.

# This software is provided "AS IS", without any express or implied warranties. The software is in the
# development stage. It is intended exclusively for experts who have experience with such software and
# solely for the purpose of inspection. All implied warranties of non-infringement, merchantability
# and fitness for a particular purpose are hereby disclaimed and excluded.

# Any dispute, controversy or claim arising under or in relation to providing this software shall be
# submitted to and settled by the final, binding jurisdiction of the courts of Munich, Germany in
# accordance with the laws of the Federal Republic of Germany excluding its conflict of law rules and
# the United Nations Convention on Contracts on the International Sales of Goods.

function usage {
    echo
    echo "Usage:"
    echo "      smoke_test_limiter.sh TEST RF FORMAT"
    echo ""      
    echo "      TEST - test branch name"
    echo "      RF - render frame size for the test branch name"
    echo "      FORMAT - test only a specific format"
    exit
}

function cleanup_decdirs {
    find $test_dir_out/dec/ -maxdepth 1 -name '*.wav' -delete 
    find $test_dir_out/dec/ -maxdepth 1 -name '*.csv' -delete 
    find $test_dir_out/dec/ -maxdepth 1 -name '*.met' -delete 
    find $test_dir_out/logs/ -maxdepth 1 -name '*.txt' -delete 
}

function cleanup_encdirs {
    find $test_dir_out/enc/ -maxdepth 1 -name '*.192' -delete 
}


function run_test {
    
    if [ -z "$4" ] ; then
        $run_base_command $2 -D="$3" --create_limiter_info $1| tee smoke_test_limiter:output$1.txt
    else
        $run_base_command $2 -D="$3 $4" --create_limiter_info $1 | tee smoke_test_limiter_output$1.txt
    fi
   
    mv $test_dir_out/run.txt test_run$1.txt
    cleanup_decdirs

}

git_url_src="git@forge.3gpp.org:ivas-codec-pc/ivas-codec.git"
git_url_ltv="git@forge.3gpp.org:ivas-codec-pc/ivas-pc-testfiles.git"
git_branch_ltv="longer-testv-on-runners"
root_dir=$PWD
ltv_dir="$PWD/ltv"
check="LIMITER"

if [ -z "$1" ] ; then
    usage
else
    test=$1
fi

if [ -z "$2" ] ; then
    test_render_size_cmd="-fr 20"
else
    test_render_size_cmd="-fr $2"
fi

if [ -z "$3" ] ; then
    restrict_format=0
    restricted_format_command=""
    restricted_format=$3
else
    restrict_format=1
    restricted_format="$3"
    restricted_format_command="-C $3"
fi


disable_limiter=1

test_dir=$root_dir/$test

# get long test vectors

if [ ! -d $ltv_dir ] ; then
    git clone --single-branch --branch $git_branch_ltv $git_url_ltv $ltv_dir
else
    cd $ltv_dir
    git pull
    cd $root_dir
fi

# get test branch

if [ ! -d $test_dir ]; then
    # check if branch exists
    if git ls-remote $git_url_src $test ; then
        # clone it
        git clone --single-branch --branch $test $git_url_src $test
    else
        echo "$test does not exist on 3gppforge"
        exit 1
    fi
    #cd $test_dir
    #CFLAGS=-DDISABLE_LIMITER make -j
    #cd $root_dir
else
    # update
    cd $test_dir
    git reset --hard
    git pull
    #make clean
    #CFLAGS=-DDISABLE_LIMITER make -j
    cd $root_dir
fi

#test_render_size_cmd="-fr $render_framesize_test"
test_dir_out="$root_dir/$test_dir/$check/"

#cleanup 
if [ -d $test_dir_out ] ; then
    cleanup_decdirs
    cleanup_encdirs
fi 

WORKERS=""


cfg=$root_dir/ci_linux.json
testv_dir=$test_dir/scripts/testv
dly_profile=$test_dir/scripts/dly_error_profiles/dly_error_profile_10.dat
fer_profile=$test_dir/scripts/dly_error_profiles/ep_15pct.g192
duration_arg="-U 10"
#verbosity_cmd="-z console"
verbosity_cmd=""

test_bitexact_base_command="$test_dir/scripts/testBitexact.py --filedirref $ref_dir/dec --filedirtest $test_dir_out/dec $WORKERS $verbosity_cmd"
run_base_command="$test_dir/scripts/IvasBuildAndRunChecks.py  -p $cfg --check $check $duration_arg $WORKERS $verbosity_cmd"
echo $run_base_command
headrot_command="-t $testv_dir/headrot.csv"
ext_orientation_command="-t $testv_dir/headrot.csv -exof $testv_dir/headrot_case00_3000_q_combinedRotationTest.csv"
directivity_command_ir="-render_config $testv_dir/config_directivity.cfg -t $testv_dir/headrot_case04_3000_q.csv -exof $testv_dir/headrot_case00_3000_q_combinedRotationTest.csv"
directivity_command_reverb="-render_config $testv_dir/rend_config_renderer_directivity_no_binary_file.cfg -t $testv_dir/headrot_case04_3000_q.csv -exof $testv_dir/headrot_case00_3000_q_combinedRotationTest.csv"
early_reflection_command="-render_config $testv_dir/rend_config_ER_v1.cfg"
hrtf_dir=$test_dir/scripts/binauralRenderer_interface/binaural_renderers_hrtf_data/
decoder_only_command="--decoder_only"
jbm_command="-J $dly_profile"
fec_command="-f $fer_profile"
# prepare config file
if [ -f $cfg ] ; then
    rm $cfg
fi
cp $root_dir/ci_linux_template.json $cfg

# only save with directory names without any .
tools_dir=$test_dir/scripts/tools/Linux
# put dummy eid-xor there, not really needed, but the script complains if it is not there
#touch $tools_dir/eid-xor
sed -i "s/{ltv_dir}/${ltv_dir////\\/}/g" $cfg 
sed -i "s/{testv_dir}/${testv_dir////\\/}/g" $cfg
sed -i "s/{tools_dir}/${tools_dir////\\/}/g" $cfg

# run all modes vanilla-fashion
# treat ISM modes separately because passing the metadata files to MASA modes causes crashes
if [ $restrict_format -eq 1 ] ; then
    ism_modes=$($test_dir/scripts/runIvasCodec.py -l -C $restricted_format | grep ^ISM )
    non_ism_modes=$($test_dir/scripts/runIvasCodec.py -l -C $restricted_format | grep -v ^ISM)
else
    ism_modes=$($test_dir/scripts/runIvasCodec.py -l | grep ^ISM )
    non_ism_modes=$($test_dir/scripts/runIvasCodec.py -l | grep -v ^ISM)
fi
#non_ism_modes=HOA3_b96_fb_cbr
if [[ ! -z "$non_ism_modes" ]] ; then 
    echo "\n======================= 1. non-ism modes no FEC =======================\n\n"
    run_test "_non_ism_default" "-m $non_ism_modes" "$test_render_size_cmd" ""
fi
if [[ ! -z "$ism_modes" ]] ; then 
    echo "\n======================= 2. ism modes no FEC =======================\n\n"
    run_test "_ism_default" "-m $ism_modes" "$test_render_size_cmd" ""
fi
#run the decoding again, but with 15% frame loss
echo "\n======================= 3. all modes with FEC =======================\n\n"
run_test "_fec" "$decoder_only_command $fec_command $restricted_format_command" "$test_render_size_cmd" ""

#run the decoding again, but with JBM
echo "\n======================= 4. all modes with JBM =======================\n\n"
run_test "_jbm" "$decoder_only_command $jbm_command $restricted_format_command" "$test_render_size_cmd" ""

# run all modes with binaural output using external files
modes_with_bin_out="FOA HOA2 HOA3 PlanarFOA PlanarHOA2 PlanarHOA3 OSBA  OMASA MASA MC ISM1 ISM2 ISM3 ISM4 ISM+1 ISM+2 ISM+3 ISM+4"
if [ $restrict_format -eq 1 ] ; then
    modes_with_bin_out=`echo $modes_with_bin_out | grep -o ${restricted_format} `
fi
if [[ ! -z "$modes_with_bin_out" ]] ; then 
    bin_out_modes="BINAURAL BINAURAL_ROOM_IR BINAURAL_ROOM_REVERB"
    echo $bin_out_modes
    echo $modes_with_bin_out
    # only head rotation 
    echo "\n======================= 5. binaural out with head rotation =======================\n\n"
    run_test "_headrot" "$decoder_only_command --oc $bin_out_modes -C $modes_with_bin_out" "$test_render_size_cmd" "$headrot_command"

    # head rotation and ext orientation
    echo "\n======================= 6. binaural out with head rotation and ext orientation =======================\n\n"
    run_test "_ext_orientation" "$decoder_only_command --oc $bin_out_modes -C $modes_with_bin_out" "$test_render_size_cmd" "$ext_orientation_command"

    # head rotation and ext orientation, JBM
    echo "\n======================= 7. binaural out with head rotation and ext orientation (JBM) =======================\n\n"
    run_test "_ext_orientation_jbm" "$decoder_only_command --oc $bin_out_modes -C $modes_with_bin_out $jbm_command" "$test_render_size_cmd" "$ext_orientation_command"

    # early reflections
    bin_out_modes="BINAURAL_ROOM_REVERB"
    echo "\n======================= 8. binaural with early reflections =======================\n\n"
    run_test "_er" "$decoder_only_command --oc $bin_out_modes -C $modes_with_bin_out" "$test_render_size_cmd" "$early_reflection_command"

    bin_out_modes="BINAURAL BINAURAL_ROOM_IR"
    echo "\n======================= 9. binaural out with HRTF files - WB =======================\n\n"
    wb_modes=$($test_dir/scripts/runIvasCodec.py -l -C $modes_with_bin_out | grep _wb_)
    hrtf_wb="$hrtf_dir/ivas_binaural_16kHz.bin"
    run_test "_hrtf_wb" "-m $wb_modes $decoder_only_command --oc $bin_out_modes" "$test_render_size_cmd" "-hrtf ${hrtf_wb}"

    echo "\n======================= 10. binaural out with HRTF files - SWB =======================\n\n"
    swb_modes=$($test_dir/scripts/runIvasCodec.py -l -C $modes_with_bin_out | grep _swb_)
    hrtf_swb="$hrtf_dir/ivas_binaural_32kHz.bin"
    run_test "_hrft_swb" "-m $swb_modes $decoder_only_command --oc $bin_out_modes" "$test_render_size_cmd" "-hrtf ${hrtf_swb}"

    echo "\n======================= 11. binaural out with HRTF files - FB =======================\n\n"
    fb_modes=$($test_dir/scripts/runIvasCodec.py -l -C $modes_with_bin_out | grep _fb_)
    hrtf_fb="$hrtf_dir/ivas_binaural_48kHz.bin"
    run_test "_hrft_fb" "-m $fb_modes $decoder_only_command --oc $bin_out_modes" "$test_render_size_cmd" "-hrtf ${hrtf_fb}"
fi

# with directivity
formats_with_directivity="ISM+1 ISM+2 ISM+3 ISM+4"
if [ $restrict_format -eq 1 ] ; then
    formats_with_directivity=`echo $formats_with_directivity | grep -o ${restricted_format} `
fi
if [[ ! -z "$formats_with_directivity" ]] ; then
    echo "\n======================= 7. binaural out with head rotation and ext orientation and directivity =======================\n\n"
    run_test "_directivity_ir" "$decoder_only_command --oc BINAURAL_ROOM_IR -C $formats_with_directivity" "$test_render_size_cmd" "$directivity_command_ir"
    run_test "_directivity" "$decoder_only_command --oc BINAURAL_ROOM_REVERB BINAURAL -C $formats_with_directivity" "$test_render_size_cmd" "$directivity_command_reverb"
fi 

