#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
    xv extractor
    Convert xv to flv
    Copyright: Ted <xiao.xj@gmail.com>
    License: BSD
"""

import sys
from glob import glob
from os import rename
from os.path import basename,exists
from collections import namedtuple
import tempfile
import re

def hash_value(vals):
    return (0xff&(vals[0]-vals[1]))*13*13 \
     +(0xff&(vals[1]-vals[2]))*13+(0xff&(vals[2]-vals[3]));

def shift_char(val,shift):
    return chr((ord(val)+shift)&0xff)

def converts(file_name):
    input_file = open(file_name,"rb") #binary file
    fname=tempfile.mktemp(suffix=".dat",dir=".");
    output_file =open(fname,"wb")
    input_file.seek(0x200000)
    buffer = input_file.read(0x400)
    MediaFile = namedtuple('Media', 'id suffix')
    #check magic bits
    known_type={}
    #FLV
    known_type[hash_value([0x46, 0x4C, 0x56, 0x01])]=MediaFile(0x46,".flv")
    #.RMF
    known_type[hash_value([0x2E, 0x52, 0x4D, 0x46])]=MediaFile(0x2E,".rmvb")
    curr_type=hash_value([ord(x) for x in buffer[:4]])
    media_file=known_type.get(curr_type)
    if media_file == None:
        print "error, invalid file ",curr_type,hash_value([0x46, 0x4C, 0x56, 0x01])
        return
    
    rot_value=media_file.id-ord(buffer[0])
    #print "value is",rot_value  
    #convert
    for x in buffer:
        output_file.write(shift_char(x,rot_value))
            
    while True:
        buffer=input_file.read(8192*1024)
        if not buffer:
            break
        output_file.write(buffer)
        
    output_file.close()
    input_file.close()
    #rename temp file and add suffix
    target_file=re.sub("\.xv$",media_file.suffix,basename(file_name))
    
    if not exists(target_file):
        rename(fname,target_file)
        fname=target_file
        print " --> ",fname
    else:
        print "created temp file ",fname
    
if __name__ == '__main__' :
    if len(sys.argv)>1:
        for docname in sys.argv[1:]:
	    print docname,
            converts(docname)
    else:
          print 'Usage:./xv2flv.py *.xv'