#! /usr/bin/env python
"""
This program will allow annotating without taking your fingers off of the keyboard.
Copyright (C) 2006  Scott Shawcroft

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

This program will allow annotating without taking your fingers off of the keyboard.
It will automatically store start and stop times along with the text.
"""
#This program pulls screenshots at times defined in the given cmml file.
import xml.dom.minidom
import pygst
pygst.require ("0.10")
import gst
import sys
import os

def to_ms(string):
  time = string.split(":")
  if len(time)==3:
    h,m,s = time
    if s.find(".")!=-1:
      s,ms = s.split(".")
      ms = ms + "0"*(3-len(ms))
      s += ms
  elif len(time)==2:
      m,s = time
      h = "0"
      ms = str(1000*int(s))
  return int(h)*3600*1000 + int(m)*60*1000 + int(ms)

class pull_thumbs:
  clip = 0
  #Function to write screenshot.
  def process(self,element,buffer,pad):
    filename = self.directory +"/"+ self.file_str + str(self.clip) + ".png"
    f = open(filename,"w")
    print "Wrote: " + filename
    f.write(str(buffer))
    f.close()
    
  def main(self,location,quality,subdir=True,dimensions=None):
    #Setup the pipeline. filesrc location=source ! decodebin ! ffmpegcolorspace ! pngenc ! fakesink
    pipeline = gst.parse_launch("filesrc name=source ! decodebin ! ffmpegcolorspace ! videoscale ! video/x-raw-rgb,width=160,height=90 ! pngenc compression-level=" + str(quality) + " ! fakesink name=sink")
    fakesink = pipeline.get_by_name("sink")
    fakesink.props.signal_handoffs = True
    fakesink.connect("preroll-handoff", self.process)
    filesrc = pipeline.get_by_name("source")
    
    f = open(location,"r")
    doc = xml.dom.minidom.parse(f)
    file_imports = doc.getElementsByTagName('import')
    for node in file_imports:
      current_file = node.getAttribute('src')
    filesrc.props.location = current_file
    
    self.location = location
    self.subdir = subdir
    if subdir:
      self.directory = current_file.rsplit(".",1)[0]
      os.mkdir(self.directory)
      self.file_str = ""
    else:
      self.directory,self.file_str = current_file.rsplit("/",1)
      self.file_str = self.file_str.rsplit(".",1)[0]   
    
    pipeline.set_state(gst.STATE_PAUSED);
    clips = doc.getElementsByTagName('clip')
    for node in clips:
      # stall script for pipeline
      if node.getAttribute('track')=="default" or not node.getAttribute('track'):
        pipeline.get_state()
        start_time = node.getAttribute('start')
        print start_time
        pipeline.seek(1.0, gst.FORMAT_TIME, gst.SEEK_FLAG_FLUSH | gst.SEEK_FLAG_ACCURATE, gst.SEEK_TYPE_SET, gst.MSECOND*to_ms(start_time), gst.SEEK_TYPE_NONE, 0)
        self.clip += 1
    pipeline.get_state()
    f.close()
    
if __name__ == "__main__":
  if len(sys.argv) > 1:
    pull = pull_thumbs()
    pull.main(sys.argv[1],8)