import sys

import gobject
import gst
import OpenGL.GL.shaders as shaders

gobject.threads_init()

import glitch, glitch.gtk
from glitch.gst import VideoLoop

import OpenGL.GL.shaders as shaders

class VideoBlend(glitch.Shader):
    vertex = """
        void main()
        {
            gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
            gl_TexCoord[0] = gl_MultiTexCoord0;
        }
        """

    fragment = """
        uniform sampler2D video1;
        uniform sampler2D video2;

        void main()
        {
            gl_FragColor = texture2D(video1, gl_TexCoord[0].st) / 2.0 +
                           texture2D(video2, gl_TexCoord[0].st) / 2.0;
        }
        """

    def set_uniforms(self, ctx, shader):
        loc = shaders.glGetUniformLocation(shader, 'video1')
        shaders.glUniform1i(loc, 0)
        loc = shaders.glGetUniformLocation(shader, 'video2')
        shaders.glUniform1i(loc, 1)

if __name__ == '__main__':
    loop1 = VideoLoop(sys.argv[1])
    loop2 = VideoLoop(sys.argv[2])

    pipeline = gst.Pipeline()
    pipeline.add(loop1.bin)
    pipeline.add(loop2.bin)
    pipeline.set_state(gst.STATE_PLAYING)

    camera = glitch.gtk.GtkCamera(eye=[0.5, 0.5, 1], ref=[0.5, 0.5, 0], children=[
        glitch.ApplyTexture(loop1, unit=0, children=[
            glitch.ApplyTexture(loop2, unit=1, children=[
                VideoBlend(children=[
                    glitch.TexturedRectangle()])])])])
    loop1.connect('new-buffer', lambda *args: camera.refresh())
    loop2.connect('new-buffer', lambda *args: camera.refresh())
    camera.run()
    pipeline.set_state(gst.STATE_NULL)

