#!/usr/bin/python

"""
Little script to convert Realaudio stream to mp3

To use it you need:
- mplayer with win32 codecs
- lame to encode the wav in mp3
- by default the wav and mp3 file are stored in your $HOME



Copyright Jkx 2004 / Licence GPL
"""



import os
import sys
import string 



# change this if you want
path=os.getenv('PWD')



hr = "*" * 78
def rip(url,filename):
    """ ripping the stream """
    os.system('mplayer -cache 10 -ao pcm -aofile %s  %s' % (filename,url))
    
def encode(filename):
    """ encode the stream w/ lame and delete it """
    dest=filename[:-4] + '.mp3'
    os.system('lame %s %s' % (filename,dest) )
    os.system('rm %s' %  filename)
    


def parseRAMFile(ramFile):
    if ramFile.startswith('http://'):
        # this is a url not a file
        import urllib
        f=urllib.urlopen(ramFile)
    else:
        try:
            f = open(ramFile)
        except IOError:
            print "Unable to open ramFile %s ... stop..." % ramFile
            return None,None

    
    data = f.readlines()
    url = None

    for line in data:
        if line.startswith('rtsp://'):
            url = line.strip()
            break
        
    if url:
        print 'Found a rtsp stream at:'
        print url

        filename=string.split(url,'/')[-1]
        if filename.endswith('.rm'):
            return url,filename[:-3]+'.wav'
        else:
            print "Unable to find the ram file stop...."
            return None,None

    else:
        print "Unable to find the rtsp stream ..."
    return None,None
    
        
    
def main():
    print hr
    url,filename = parseRAMFile(sys.argv[1])
    if url and filename:
        destfile = os.path.join(path,filename)
        print "Rip file in %s" % destfile
        print hr
        rip(url,destfile)
        print hr
        encode(destfile)
        print "Finish...."
        print hr

        
    else:
        print "Something go wrong ...."
        print hr


def usage():
    me = sys.argv[0]
    print "Convert realaudio to mp3 / usage:"
    print "   %s ramfile.ram" % me
    print "   %s http://XXXX/stream.ram" % me
    print " * files will be stored in %s" % path

if __name__ == '__main__':
    if len(sys.argv) < 2:
        usage()
    else:
        main()
    
