import string, Image, ImageDraw, ImagePalette, ImageFont
import os, sys





## EDIT THIS
width = 720;
height = 576;
fontsize = 32;
font = ImageFont.truetype("/usr/share/fonts/truetype/ttf-bitstream-vera/Vera.ttf", fontsize)

if (len(sys.argv) < 2):
    print "usage:  python makespumux.py   subfile.srt"
    quit();
#srtfile is your subtitle file, something like "kaos_en.srt" 
#it must have an .srt ending
srtfile = sys.argv[1]

## Should be ok from here down
######################################
basenameimg = "sub_en"

p  =  srtfile.split(".")[0]
basenameimg = p + "/sub";
spumuxfile = p + "/spu.xml"

cmd="mkdir -p " + p
os.system(cmd)

def IsInt( str ):
    """ Is the given string an integer? """
    ok = 1
    try:
        num = int(str)
    except ValueError:
        ok = 0
    return ok

def makeSubImage( filename, t):
    """make a 3color png for DVD subtitles"""
    im = Image.new('P',(width, height), 2 )
    palette = []
    palette.extend( ( 255,255,255 )  )
    palette.extend( ( 0,0,0 )  )
    im.putpalette(palette)
    draw = ImageDraw.Draw(im);

    c = 0;
    splitpnt  = 0;
    max = -1
    lines = [];

    while( max < 0 or max > (width - 70) ):
        ## we need to find out how many lines to make
        max = -1;
        c = c + 1;
        splitpnt = 0;
        lines = []; 
        for i in range(1,c+1):
            lo = splitpnt;
            end = i * ( len(t)/c);
            #print "end = " + str(end);
            splitpnt = t.rfind(' ', 0,  end )
            if (i == c):
                splitpnt = len(t);
            #print str(lo) + ":" + str(splitpnt);
            line = t[lo:splitpnt]
            line = line.lstrip();
            line = line.rstrip();
            lines.append(line) ;
            tmp = draw.textsize( line, font=font);
            if (tmp[0] > max ):
                max = tmp[0];
            #print str(i) + ' = ' + line 
            #print "max = " + str(max) 
        if (c > 5):
            quit();
    c =0
    for i in lines:
        print i
        tsize = draw.textsize( i, font=font);
        x = (width - tsize[0] ) / 2; 
        y = height - (( tsize[1] * (len(lines) - c ) ) + 34);
        c = c +1;
        draw.text( (x +2 ,y +2), i, font=font, fill=1 )
        draw.text( (x,y), i, font=font, fill=0 )
    
    im.save( filename, "PNG", transparency=2)


fd = file( srtfile , 'r')
all = fd.readlines( )
fd.close()
count =0;
oldcount =0;
stime = ('','','','');
etime = ('','','','');
text ='';
time ='';

spumux = "<subpictures>\n<stream>\n";



for i in all:
    x = i.rstrip("\n")
    if (x == '') and (count != oldcount):
        starttime = stime[0] + ':' + stime[1] +  ':' +  stime[2] + '.' +  stime[3][0:2] ;
        endtime = etime[0] + ':' + etime[1] +  ':' +  etime[2] + '.' +  etime[3][0:2] ;
        print '----------------------'
        #print 'count = ' + str(count)
        #print 'time = ' + starttime + ' | ' + endtime ;
        #print str(count) + ' = ' + text
        print str(count) 
        outname = basenameimg + str(count) + ".png";
        makeSubImage( outname, text);
        oldcount = count;
        text = '';
        spumux += '<spu start="' + starttime + '" end="' + endtime + '" image="' + outname + '"  />' + "\n"
    else:
        if (IsInt(x)):
           count = int(x);
        elif ( x.find("-->" ) == -1 ):
            text += x + ' ';
        else:
            tmp = x.split("-->")
            tmp[0] = tmp[0].lstrip();
            tmp[0] = tmp[0].rstrip();
            tmp[1] = tmp[1].lstrip();
            tmp[1] = tmp[1].rstrip();
            
            s = tmp[0].split(':');
            e = tmp[1].split(':');
            s1 = s[2].split(',');
            e1 = e[2].split(',');
            
            stime = ( s[0], s[1], s1[0], s1[1]);
            etime = ( e[0], e[1], e1[0], e1[1]);
                
            time = tmp[0] + '-'+ tmp[1];   


            
            
spumux += "</stream>\n</subpictures>\n";

fd = file( spumuxfile, 'w');
fd.write(spumux);
fd.close;
 
