#!/usr/bin/python
#
# LiveCut
# (c) 2002-2003 Jerome Alet <alet@librelogiciel.com>
# You're welcome to redistribute this software under the
# terms of the GNU General Public Licence version 2.0
# or, at your option, any higher version.
#
# You can read the complete GNU GPL in the file COPYING
# which should come along with this software, or visit
# the Free Software Foundation's WEB site http://www.fsf.org
#
# $Id: lvc2smile,v 1.1 2003/03/13 14:01:59 jalet Exp $
#
#


import sys
try :
    import jaxml
except ImportError :    
    sys.stderr.write("You need to install the JAXML python module, available from :\n\thttp://www.librelogiciel.com/software/\n")
    sys.exit(-1)

class SMILE_document(jaxml.XML_document) :
    def __init__(self, author="", copyright="", title="", clip="") :
        jaxml.XML_document.__init__(self)
        self._clip = clip
        self._author = author
        self._copyright = copyright
        self._title = title
        
    def _normalizeName(self, name) :    
        return name.strip().lower().replace(' ', '_')
        
    def _genRealText(self, message) :    
        # because the <text> tag doesn't work well with RealPlayer 8, we
        # use RealText instead.
        fname = "%s.rt" % self._normalizeName(message)
        rt = jaxml.XML_document()
        rt.window(bgcolor="black", height="32", width="352")
        rt.font(face="Helvetica", color="yellow", charset="iso-8859-1")
        rt.center()
        rt.b(message)
        lines = '\n'.join(str(rt).split('\n')[1:])
        file = open(fname, "w")
        file.write(lines)
        file.close()
        return fname
        
    def _readTimeLine(self, timeline) :    
        for line in [l for l in timeline if not l.startswith('#')] :
            parts = [part.strip() for part in line.split()]
            if len(parts) == 5 :
                parts.append("")
            elif len(parts) > 6 :    
                part = " ".join(parts[5:])
                del parts[5:]
                parts.append(part)
            (event, dummy, guitimecode, dummy, dvtimecode, description) = parts
            getattr(self, "_event%s" % event)(dvtimecode, description)
        
    def _eventSpeaker(self, timecode, description) :
        if not self._inSpeaker :
            self._inSpeaker = 1
            self._slideNumber = 1
        else :     
            (h, m, s, ms) = self._lastSpeakerTimeCode.split(':')
            begin = "%s:%s:%s.%s" % (h, m, s, ms)
            (h, m, s, ms) = [int(t) for t in (h, m, s, ms)]
            startms = h*3600000 + m*60000 + s*1000 + ms
            (h, m, s, ms) = timecode.split(':')
            end = "%s:%s:%s.%s" % (h, m, s, ms)
            (h, m, s, ms) = [int(t) for t in (h, m, s, ms)]
            duration = (h*3600000 + m*60000 + s*1000 + ms) - startms
            self._push()
            self.par(id="speaker%i" % self._inSpeaker, title=self._lastSpeakerName, author=self._author, copyright=self._copyright, endsync="first")
            self._push()
            self.video({"clip-begin" : begin, "clip-end" : end}, src=self._clip, region="video", title=self._lastSpeakerName, author=self._author, copyright=self._copyright)
            self._pop()
            rtfname = self._genRealText(self._lastSpeakerName)
            self._push()
            self.textstream(src=rtfname, fill="freeze", region="title", title=self._lastSpeakerName, author=self._author, copyright=self._copyright, dur="%ims" % duration)
            self._pop()
            totalduration = 0
            for i in range(1, len(self._speakerSlides) + 1) :
                if i == 1 :
                    self.seq()
                prec = i - 1
                (tc, desc) = self._speakerSlides[prec]
                (h, m, s, ms) = [int(t) for t in tc.split(':')]
                endms = h*3600000 + m*60000 + s*1000 + ms
                self._push()
                try :
                    (tc, desc) = self._speakerSlides[i]
                    (h, m, s, ms) = [int(t) for t in tc.split(':')]
                    newms = h*3600000 + m*60000 + s*1000 + ms
                    if not prec :
                        self.img(fill="freeze", src="%i.gif" % self._slideNumber, region="slide", begin="%ims" % (endms - startms), dur="%ims" % (newms - endms))
                    else :    
                        self.img(fill="freeze", src="%i.gif" % self._slideNumber, region="slide", dur="%ims" % (newms - endms))
                    totalduration += (newms - endms)
                except IndexError :    
                    self.img(fill="freeze", src="%i.gif" % self._slideNumber, region="slide", dur="%ims" % (duration - (endms - startms)))
                self._pop()
                self._slideNumber += 1
            self._pop()
            self._inSpeaker += 1
        self._lastSpeakerTimeCode = timecode
        self._lastSpeakerName = description
        self._speakerSlides = []
        
    def _eventSlide(self, timecode, description) :    
        self._speakerSlides.append((timecode, description))
        
    def _eventStart(self, timecode, description) :    
        self.smil()
        self._push()
        self.head()
        self._push()
        self.meta(name="author", content=self._author) 
        self._pop()
        self._push()
        self.meta(name="copyright", content=self._copyright) 
        self._pop()
        self._push()
        self.meta(name="title", content=self._title) 
        self._pop()
        self.layout()
        self._push()
        getattr(self, "root-layout")(width="704", height="328")
        self._pop()
        self._push()
        # 352x288
        self.region(id="video", top="0", left="0", width="352", height="288")
        self._pop()
        self._push()
        self.region(id="slide", top="24", left="368", width="368", height="240")
        self._pop()
        self._push()
        self.region(id="title", top="288", left="0", width="352", height="32")
        self._pop()
        self._pop()
        self.body()
        self.seq()
        self._inSpeaker = 0
        
    def _eventStop(self, timecode, description) :    
        pass
        
    def _eventSkipStart(self, timecode, description) :    
        pass
        
    def _eventSkipStop(self, timecode, description) :    
        pass
        
def main() :
    nargs = len(sys.argv) 
    if nargs != 5 :
        sys.stderr.write("usage :  lvc2smile  title  rmfile  inputfile  outputfile\n")
    else :    
        title = sys.argv[1]
        rmfile = sys.argv[2]
        input = open(sys.argv[3])
        timeline = input.readlines()
        input.close()
        sys.stderr.write("Please edit lvc2smile to put your name and copyright messages in, they currently can't be modified by command line options, but this will come in a future version !\n")
        x = SMILE_document("Your Name Here : Edit lvc2smile", "(c) Your Name Here : Edit lvc2smile", title, rmfile)
        x._readTimeLine(timeline)
        x._output(sys.argv[4])
        
if __name__ == "__main__" :
    main()
