#!/bin/bash

# get all the Ogg Theora files from a tmp dir where they were linked
# this command can be interrupted and continued because of "-c" param
# puf -r -c http://mirror.linux.org.au/linux.conf.au/2007/video/tmp/

# go through directories and rip and encode files
for directory in *; do

 # go through files
 for file in $directory/*.ogg; do

   basis_name=`basename $file .ogg`
   vorbisname=$directory/$basis_name.vrb
   wavname=$directory/$basis_name.wav
   soxname=$directory/$basis_name.sox.wav
   speexname=$directory/$basis_name.spx

   # find out if file has 1 or 2 audio channels
   echo "oggzinfo $file | grep \"Channels\" | sed -e 's/Audio-Channels://g'"
   channels=`oggzinfo $file | grep "Channels" | sed -e 's/Audio-Channels://g'`
   echo $channels

   # extract vorbis from theora file
   echo "oggzrip -c vorbis -o $vorbisname $file"
   oggzrip -c vorbis -o $vorbisname $file

   # decode vorbis to wav
   echo "ogg123 -d wav -f $wavname $vorbisname"
   ogg123 -d wav -f $wavname $vorbisname

   # normalize audio
   echo "normalize-audio $wavname"
   normalize-audio $wavname

   # downsample audio to 8kHz
   echo "sox -c $channels -r 48000 -t sw $wavname -r 8000 -c 1 -t sw $soxname"
   sox -c $channels -r 48000 -t sw $wavname -r 8000 -c 1 -t sw $soxname

   # encode downsampled file to speex
   echo "speexenc -V --quality 4 $soxname $speexname"
   speexenc -V --quality 4 $soxname $speexname

   # clean up
   echo "rm $soxname $wavname $vorbisname"
   rm $soxname $wavname $vorbisname

 done

done
