from opencv.cv import *
from opencv.highgui import *

EVENTS = ['CV_EVENT_MOUSEMOVE', 'CV_EVENT_LBUTTONDOWN', 'CV_EVENT_RBUTTONDOWN',  'CV_EVENT_MBUTTONDOWN',  'CV_EVENT_LBUTTONUP',  'CV_EVENT_RBUTTONUP', 'CV_EVENT_MBUTTONUP'  , 'CV_EVENT_LBUTTONDBLCLK','CV_EVENT_RBUTTONDBLCLK','CV_EVENT_MBUTTONDBLCLK']

capture = cvCreateFileCapture("c:/street.avi")
frames = []

print "Video has ", str(cvGetCaptureProperty(capture, 7)), " frames"

for k in range(0, int(cvGetCaptureProperty(capture, 7))):
	if (k % 15 == 0):
		frame = cvQueryFrame(capture)
		tempFrame = cvCreateMat(frame.height, frame.width, frame.type)
		cvCopy(frame, tempFrame)
		cvFlip(tempFrame)
		frames.append(tempFrame)
	if (k % 10 == 0):
		print "... ", str(k), " frames processed..."

slit_position = 0
mousedown = False
tempFrame = cvCreateMat(frame.height, frame.width, frame.type)

def timeline_mouse(event, x, y, flags, params):
	global mousedown
	global timeline
	global camera
	if EVENTS[event] == 'CV_EVENT_LBUTTONDOWN':
		mousedown = True
	elif EVENTS[event] == 'CV_EVENT_LBUTTONUP':
		mousedown = False
	if mousedown == True and x > 0 and x < timeline.width and y > 0 and y < timeline.height:
		camera = frames[x]
		slit_change(camera)
		cvShowImage("camera", tempFrame)

def camera_mouse(event, x, y, flags, params):
	global mousedown
	global frames
	global camera
	global tempFrame
	global slit_position
	if EVENTS[event] == 'CV_EVENT_LBUTTONDOWN':
		mousedown = True
	elif EVENTS[event] == 'CV_EVENT_LBUTTONUP':
		mousedown = False
	if mousedown == True and x > 0 and x < frames[0].width and y > 0 and y < frames[0].height:
		slit_position = x
		slit_change(camera)
		cvShowImage("camera", tempFrame)
		constructTimeline(x)
		cvShowImage("timeline", timeline)

def slit_change(frame):
	global slit_position
	global tempFrame
	cvZero(tempFrame)
	cvCopy(frame, tempFrame)
	cvLine(tempFrame, cvPoint(slit_position, 0), cvPoint(slit_position, frame.height), cvScalar(0, 0, 255))

def constructTimeline(y):
#def constructTimeline(time, y):
	for x in range(0, len(frames)):
		timeline[:,x] = frames[x][:,y]
#	cvZero(timeline[:,time])

cvStartWindowThread()
cvNamedWindow("timeline")
cvNamedWindow("camera")

timeline = cvCreateMat(frames[0].height, len(frames), frames[0].type)
camera = frames[0]
constructTimeline(0)
slit_change(camera)
cvShowImage("timeline", timeline)
cvShowImage("camera", tempFrame)

cvSetMouseCallback("timeline", timeline_mouse)
cvSetMouseCallback("camera", camera_mouse)

cvWaitKey()

