import os
import sys
import time
from gi.repository import Clutter, GtkClutter, Gst

gst_source_description = "v4l2src device=/dev/video0 ! " + \
    "queue ! " + \
    "video/x-raw,format=YUY2,width=640,height=480,framerate=30/1 ! " + \
    "videoflip method=horizontal-flip"

Gst.init([])
GtkClutter.init([])


while True:
    pid = os.fork()

    if pid == 0:

        video_texture = Clutter.Texture()

        source = Gst.parse_bin_from_description(
            gst_source_description,
            True
        )

        wrapper = Gst.ElementFactory.make("wrappercamerabinsrc", "wrapper")
        wrapper.set_property("video-source", source)

        camerabin = Gst.ElementFactory.make("camerabin", "camera")
        camerabin.set_property("camera-source", wrapper)

        sink = Gst.ElementFactory.make("cluttersink", "videosink")
        sink.set_property("texture", video_texture)

        camerabin.set_property("viewfinder-sink", sink)

        camerabin.set_state(Gst.State.PLAYING)
        # time.sleep(0.1)   # if this line is uncommented it won't crash
        camerabin.emit("start-capture")
        sys.exit(0)

    else:
        pid, status = os.wait()
        signal = status & 0xFF

        if signal == 139:
            print "Program crashed"
            sys.exit(0)
