#!/bin/bash
#-------------------------- =+- Shell script -+= --------------------------
# @file      wma2mp3.sh
# @date      Mon Oct  3 16:28:12 2005
# @brief
#
#
#  Yaroslav Halchenko                                      CS@UNM, CS@NJIT
#  web:     http://www.onerussian.com                      & PSYCH@RUTGERS
#  e-mail:  yoh@onerussian.com                              ICQ#: 60653192
#
# DESCRIPTION (NOTES):
#
#   Cruel script to reencode wma into mp3
#
#   Features:
#     - tries to preserve stereo/mono and bitrate
#     - does it through the pipe, thus no temp files taking up the disk
#       space
#   Depends:
#     mplayer, lame
#   Examples:
#     Convert all wma files into mp3 if there is no mp3 file already
# find -iname \*.wma -print0 \
#  | xargs -n 1 -i% -0 bash -c 'f="%"; [ -f "${f//.wma/.mp3}" ] && wma2mp3.sh "$f"'
#-----------------\____________________________________/------------------


# olderish version
# fifo=/tmp/fout1111

# better one although still crappy since mktemp doesn't open fifo
fifo=`mktemp -t fout.XXXXXX`
[ ! -p "$fifo" ] && ( rm -rf "$fifo";  mkfifo "$fifo" )

file="$*"
fileout="${file%.*}.mp3"
echo -e -n "Working on $file => $fileout"

# Get  parameters of the original file
eval `mplayer -identify -frames 0 -vo null "$file" 2>/dev/null | \
      grep 'AUDIO_.*\(RATE\|NCH\)' | sed -e 's/^/export /g'`
sleep 2
echo "ID_AUDIO_NCH=$ID_AUDIO_NCH"

# Doesn't work because stupid transcode forces -x (byteswap) for lame
# monostereo=('0' '2' '1')
# transcode -i "$file" -x null,mplayer -y null,lame -N 0x55 -b ${ID_AUDIO_BITRATE%???},0,9,${monostereo[$ID_AUDIO_NCH]}  -o "$fileout"
#exit 0

monostereo=('X' 'm' 's')

# first simple one via mplayer/lame
#mplayer -quiet -hardframedrop -vo null -vc dummy -af resample=$ID_AUDIO_RATE \
mplayer -quiet -hardframedrop -vo null -vc dummy  \
	-ao pcm:waveheader -ao pcm:file=$fifo "$file"  &>/dev/null &

lame --quiet -cbr -m ${monostereo[$ID_AUDIO_NCH]} \
	-b `echo "round(${ID_AUDIO_BITRATE}/1000)" | octave -q | awk '{print $3;}'` \
     -o - "$fileout" < $fifo
  #-b ${ID_AUDIO_BITRATE%???} -k  -o - "$fileout" < $fifo

echo " done"
rm -f $fifo

