#!/bin/sh
#
# Copyright © 2013 Jonas Smedegaard <dr@jones.dk>
# Description: Re-stream MMS stream to stdout
#
# 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, or (at your option)
# any later version.
#
# 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.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
# 02111-1307 USA.
#
# Depends: libav-tools

set -e

PRG=$(basename "$0")

showhelp() {
	cat <<EOF
Usage:   $PRG STREAM

Examples:
    $PRG bbc6 | mplayer -ignore-start -
    $PRG mms://wmlive-acl.bbc.co.uk/wms/bbc_ami/6music/6music_bb_live_ep1_sl0

Use pseudo-protocol mmsh:// for mms-over-http.

EOF
}

exit1() {
	echo "ERROR: $1"
	exit 1
}

url=
# TODO: resolve http redirections, Like BBC6:
#  http://sradio.tv/stream/489.m3u → http://www.bbc.co.uk/6music/ram/6music.asx
# TODO: Add more shortnames than BBC6
case "$1" in
	mmst:*|mmsh*) url="$1";;
	# http://www.bbc.co.uk/radio/listen/live/r1.asx
	bbc1) url=mms://wmlive-nonacl.bbc.net.uk/wms/bbc_ami/radio1/radio1_bb_live_int_ep1_sl0;;
	bbc1acl) url=mms://wmlive-acl.bbc.co.uk/wms/bbc_ami/radio1/radio1_bb_live_ep1_sl0;;
	# http://www.bbc.co.uk/radio/listen/live/r2.asx
	bbc2) url=mms://wmlive-nonacl.bbc.net.uk/wms/bbc_ami/radio2/radio2_bb_live_int_ep1_sl0;;
	bbc3acl) url=mms://wmlive-acl.bbc.co.uk/wms/bbc_ami/radio2/radio2_bb_live_ep1_sl0;;
	# http://www.bbc.co.uk/radio/listen/live/r2.asx
	bbc3) url=mms://wmlive-nonacl.bbc.net.uk/wms/bbc_ami/radio3/radio2_bb_live_int_ep1_sl0;;
	bbc3acl) url=mms://wmlive-acl.bbc.co.uk/wms/bbc_ami/radio3/radio3_bb_live_ep1_sl0;;
	# http://www.bbc.co.uk/radio/listen/live/r4.asx
	bbc4) url=mms://wmlive-nonacl.bbc.net.uk/wms/bbc_ami/radio4/radio4_bb_live_int_ep1_sl1;;
	bbc4acl) url=mms://wmlive-acl.bbc.co.uk/wms/bbc_ami/radio4/radio4_bb_live_ep1_sl0;;
	# http://www.bbc.co.uk/6music/ram/6music.asx
	bbc6) url=mms://wmlive-nonacl.bbc.net.uk/wms/bbc_ami/6music/6music_bb_live_int_ep1_sl0;;
	bbc6acl) url=mms://wmlive-acl.bbc.co.uk/wms/bbc_ami/6music/6music_bb_live_ep1_sl0;;
	*) showhelp; exit1 "unknown or missing stream";;
esac

url=`echo "$url" | perl -pe 's/^mms:/mmst:/'`

avconv -i "$url" -c copy -f avi pipe:1

# alternative methods (needs mms:// protocol URLs)
#mimms -q "$url" -
#gst-launch -q mmssrc "location=$url" '!' fdsink fd=1