#!/bin/bash

# Copyright © 2012-2026 ScriptFanix
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# A copy of the GNU General Public License v3 is includded in the LICENSE file
# at the root of the project.

decodeSox() {
	# Build a SoX decode command with optional processing (normalize,
	# resample, up/downmix)
	commandline=(${ionice}sox --single-threaded --temp "$tempdir")
	soxoptions_in=''
	soxoptions_out=''

	# Add --norm if output normalization is requested
	if (( ${destinationnormalize["$destination"]} ))
	then
		commandline+=(--norm)
		soxoptions_in+=' --norm'
	fi

	# $1 can be set to pass an already decoded file.
	# Use the the original file when unset
	if [ -n "$1" ]
	then
		commandline+=("$1")
	else
		commandline+=("$sourcepath/${filename//$'\n'/::AtOM:NewLine:SQL:Inline::}")
	fi

	# Add resampling if requested
	if [ -n "${destinationfrequency["$destination"]}" ]	\
	&& (( ${rate:-0} != ${destinationfrequency["$destination"]} ))
	then
		commandline+=(-r ${destinationfrequency["$destination"]})
		soxoptions_out+=" -r ${destinationfrequency["$destination"]}"
	fi

	# Add channel up/downmixing if requested
	if [ -n "${destinationchannels["$destination"]}" ]	\
	&& (( ${channels:-0} != ${destinationchannels["$destination"]} ))
	then
		commandline+=(-c ${destinationchannels["$destination"]})
		soxoptions_out+=" -c ${destinationchannels["$destination"]}"
	fi

	# Downsample to 16-bit if source resolution exceeds 16 bits
	if (( ${depth:-0} > 16 ))
	then
		commandline+=(-b 16)
		soxoptions_out+=" -b 16"
	fi

	# Encode all sox options into the tmpfile name so different processing
	# chains get unique WAV files
	# Avoids conflicts with different samplerate/norm/channel counts
	tmpfile="$fileid${soxoptions_in// /}${soxoptions_out// /}"
	commandline+=("$tempdir/$tmpfile.wav")
}
