#!/bin/bash
#
# AudioDiff
# by TheOuterLinux (https://theouterlinux.gitlab.io)
#
# The following script uses SoX and ImageMagick's 'compare' program to
# compare the spectrograms of two audio files created by Sox.
# The output results in a percentage from 0.000000 to 1 (100%)
# with another file in which the red pixels are the differences.
# A value of 1 means the audio files are very similar or exact
# and a value of o means they have nothing or very little in common.
# This script does not account for silence at the beginning or end of audio.
# Spectrograms made by SoX are by default 8-bit sRGB 255c.
#
# License: CC0 (Public Domain; Do Not Care)
# Last updated: 2026/10/28
#

AUDIOFILE_A="$1"
AUDIOFILE_B="$2"

function HELP(){
echo ''
echo 'AudioDiff'
echo '---------'
echo 'This script is used to create a percentage when comparing'
echo 'two audio files based on produced spectrograms.'
echo 'This comparison is made using SSIM. A value of 1 means the'
echo 'two audio files are either exact or very similar and a value'
echo 'of 0 means they have nothing in common. This script does not'
echo 'account for silence at the beginning or end of audio.'
echo 'SoX and ImageMagick are required.'
echo ''
echo 'USAGE:'
echo ''
SCRIPT="$(basename "$0")"
echo "    \"/path/to/$SCRIPT\" AudioFile_A.ext AudioFile_B.ext [--trim-silence, --trim, -t]"
echo ''
echo 'The audio file extensions (*.ext) can be anything SoX supports.'
echo ''
}

function MAIN(){
    BASENAME_A="$(basename "$AUDIOFILE_A")"
    BASENAME_B="$(basename "$AUDIOFILE_B")"
    FILE_A="/tmp/${BASENAME_A%.*}_A.png"
    FILE_B="/tmp/${BASENAME_B%.*}_B.png"
    sox "$AUDIOFILE_A" -n spectrogram -o "$FILE_A"
    sox "$AUDIOFILE_B" -n spectrogram -o "$FILE_B"
    echo ''
    echo 'AudioDiff'
    echo '---------'
    echo 'The similarity between files...'
    echo "File A: $BASENAME_A"
    echo "File B: $BASENAME_B"
    echo ''
    echo '...is...'
    PERCENTAGE_SSIM="$(compare "$FILE_A" "$FILE_B" -metric SSIM "/tmp/spectrogram_SSIM.png")"
    echo ''
    echo "$PERCENTAGE_SSIM"
}

if [ "$1" = '' ] || [ "$2" = '' ] || [ "$1" = '-h' ] || [ "$1" = '--help' ]
then
    if [ ! -f "$1" ] && [ "$1" != '' ]
    then
        echo ''
        echo "File does not exist: $1"
        echo ''
        HELP
    elif [ ! -f "$2" ] && [ "$2" != '' ]
    then
        echo ''
        echo "File does not exist: $2"
        echo ''
        HELP
    elif [ ! -f "$1" ] && [ "$1" != '' ] && [ ! -f "$2" ] && [ "$2" != '' ]
    then
        echo ''
        echo "File does not exist: $1"
        echo "File does not exist: $2"
        echo ''
        HELP
    else
        HELP
    fi
else
    MAIN
fi
