Skip to content

Instantly share code, notes, and snippets.

@mikkun
Created September 4, 2013 00:30
Show Gist options
  • Save mikkun/6431367 to your computer and use it in GitHub Desktop.
Save mikkun/6431367 to your computer and use it in GitHub Desktop.
Recording live TV stream from Ustream
#!/bin/bash
#
# rec_ustream_live: Recording live TV stream from Ustream
#
# Written by KUSANAGI Mitsuhisa(mikkun@mbg.nifty.com) / Date: 2012-09-03
tmp=/tmp/$$
ERROR_CHECK ()
{
[ "$(echo "${PIPESTATUS[@]}" |
awk 'BEGIN{RS=" "}{n+=$1}END{print n}')" -eq 0 ] && return
echo "$1" 1>&2
rm -f $tmp-*
exit 1
}
[ "$#" -ge 1 -a "$#" -le 2 ]
ERROR_CHECK 'Usage: rec_ustream_live CHANNEL_NAME [SECONDS]'
opt_duration=''
[ "$#" -eq 2 ] && opt_duration="-B $2"
wget -q "http://api.ustream.tv/json/channel/$1/getInfo?key=yourDevKey" \
-O $tmp-channel
cat $tmp-channel | grep -q '^{"results":{"id":[0-9]\+,'
ERROR_CHECK "rec_ustream_live: invalid channel name \`$1'"
channel_id=$(sed 's/^{"results":{"id":\([0-9]\+\),.*/\1/' $tmp-channel)
wget -q "http://cdngw.ustream.tv/Viewer/getStream/1/$channel_id.amf" \
-O $tmp-amf
cat $tmp-amf | tr '[:cntrl:]' '\n' | sed '/^$/d' > $tmp-work
cat $tmp-work | sed '/^status$/,+1!d' > $tmp-status
cat $tmp-status | grep -q '^online$'
ERROR_CHECK "rec_ustream_live: channel \`$1' is offline now"
cat $tmp-work | sed '/^\(cdn\|fms\)Url$/,+1!d' > $tmp-server
server_url=$(tail -n 1 $tmp-server | sed 's|^.*\(rtmp://.\+\)|\1|')
echo "$server_url" | grep -q '^rtmp://'
ERROR_CHECK "rec_ustream_live: no RTMP URL found in \`$channel_id.amf'"
cat $tmp-work | sed '/^streamName$/,+1!d' > $tmp-streamName
stream_name=$(tail -n 1 $tmp-streamName)
viewer_url=$(cat $tmp-channel |
tr -d '\\' |
sed 's|^.*<param name="movie" value="\(http://[^"]\+\)".*|\1|')
output_file="$1-$(date +%Y%m%d%H%M%S).flv"
echo "Recording to \`$output_file', press Ctrl-C to stop..."
rtmpdump -r "$server_url/$stream_name" -W "$viewer_url" -v -o "$output_file" \
-q $opt_duration
[ -s "$output_file" ]
ERROR_CHECK "rec_ustream_live: failed to record channel \`$1'"
echo
echo "Channel \`$1' recorded successfully."
rm -f $tmp-*
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment