#!/bin/sh
#
# Usage: mpx file1 file2 | esdcat
#   or
#        mpx file1 file2 | sox -t raw -c 2 -r 44100 -w -s - -t ossdsp /dev/dsp
#
# Plays two CD-quality (44100 sample/sec stereo) WAV or MP3 files
# simultaneously, sending one or the other to standard output (to be
# piped to esdcat or sox or equivalent for playback).  This allows
# direct A/B comparison between the two files.
#
# Toggling between inputs is accomplished by pressing <enter> on the keyboard.
#
# Corey Satten, corey @ cac.washington.edu, 8/29/00
# http://staff.washington.edu/corey

case "$1~~$2" in *mp3~~*mp3|*wav~~*mp3|*mp3~~*wav|*wav~~*wav);; *)
    echo "Usage: `basename $0` file1 file2 | esdcat" 1>&2; exit 1;;
esac

trap 'rm -f $PIPE4 $PIPE5 $EOF; kill 0; stty echo; exit 0' 0

PIPE4=/tmp/pipe4$$; mkfifo $PIPE4
PIPE5=/tmp/pipe5$$; mkfifo $PIPE5
EOF=/tmp/eof$$
CHUNK=50

MP3="mpg123 -z -s --stereo - |
     sox  -t raw -r 44100 -w -s -c 2 - -t sw -r 44100 -c 2 -"

case "$1" in *.mp3) eval $MP3;; *.wav) cat;; esac < $1 > $PIPE4 2>&- & 
case "$2" in *.mp3) eval $MP3;; *.wav) cat;; esac < $2 > $PIPE5 2>&- &

exec 3<&0 4< $PIPE4 5< $PIPE5

stty -echo; while read a; do kill -12 $$; done 0<&3 &	# toggle req
M=4; trap 'case "$M" in 4) M=5;; 5) M=4;; esac' 12	# toggle handler

while :; do
    case "$M" in
	4) dd bs=1k count=$CHUNK <&5 2>/dev/null 1>&2	# discard
	   dd bs=1k count=$CHUNK <&4 2>$EOF		# play
	   echo -n 1 1>&2
	   ;;
	5) dd bs=1k count=$CHUNK <&4 2>/dev/null 1>&2	# discard
	   dd bs=1k count=$CHUNK <&5 2>$EOF		# play
	   echo -n 2 1>&2
	   ;;
    esac
    case `sed -n 2p $EOF` in ''|0+0*) exit 0;; esac
done
