#!/usr/bin/env python
# -*- coding: UTF-8 -*-

# 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

from PIL import Image
import sys
import dircache

def get_fps_values(fps_str):
	
	pos=fps_str.find("/")
	if (pos==-1):
		return (float(fps_str),1.0)
	else:
		return (float(fps_str[:pos]),float(fps_str[pos+1:]))


def get_files(filter):

	a=dircache.listdir("./")
	a=a[:]
	dircache.annotate("./",a)
	b=[]
	length=len(filter)
	for element in a:
		if element[-1]=="/":
			continue
		if filter==element[:length]:
			b.append(element)
	b.sort()
	return b

# parameters: time_interpolation.py XXX/YYY AAA/BBB
# XXX/YYY is the input  FPS (like 24, 24000/1001, 30000/1001...)
# XXX/YYY is the output FPS (like 24, 24000/1001, 30000/1001...)

try:
	infps_str=sys.argv[1]
	outfps_str=sys.argv[2]
except:
	print "Usage: time_interpolation.py XXX/YYY AAA/BBB"
	print "XXX/YYY is the input  FPS (like 24, 24000/1001, 30000/1001...)"
	print "XXX/YYY is the output FPS (like 24, 24000/1001, 30000/1001...)"
	sys.exit(1)

infiles_str="0"
outfiles_str="out"


infps_a,infps_b=get_fps_values(infps_str)
outfps_a,outfps_b=get_fps_values(outfps_str)

filelist=get_files(infiles_str)

numpics=len(filelist)

if numpics<2:
	print "At least two files are needed. Exiting."
	sys.exit(1)

pic1=Image.open(filelist[0])
pic2=Image.open(filelist[1])

fr_in=0.0
fr_out=0.0

while (True):
	while(((fr_out*outfps_b)/outfps_a) >= (((fr_in+1)*infps_b)/infps_a)):
		fr_in+=1 # next input frame
		if numpics<=(fr_in):
			print "Done"
			sys.exit(0)
		pic1=pic2
		pic2=Image.open(filelist[int(fr_in+1)])
	blend_value=((fr_out*outfps_b*infps_a)-(fr_in*infps_b*outfps_a))/(outfps_a*infps_b)
	mixed_frame=Image.blend(pic1,pic2,blend_value)
	total=9-len(str(int(fr_out)))
	out_filename=outfiles_str+"0"*total+str(int(fr_out))+".png"
	print "Storing frame "+out_filename+" using frames "+str(int(fr_in))+" and "+str(1+int(fr_in))+" with blend "+str(blend_value)[:5]
	mixed_frame.save(out_filename)
	fr_out+=1
