from __future__ import with_statement

import gobject
import gst

from glitch.fbo import BufferCamera
from glitch.glx import GLXContext
from glitch.read import Read

class CameraSource(gst.BaseSrc):
    __gsttemplates__ = (
        gst.PadTemplate("src", gst.PAD_SRC, gst.PAD_ALWAYS,
            # XXX: hardcoded width and height
            gst.Caps("video/x-raw-rgb,depth=24,bpp=24,width=720,height=576")))

    def __init__(self, camera):
        gst.BaseSrc.__init__(self)

        self.camera = camera
        self.pixbuf = None

        self.start = 0
        self.stop = gst.CLOCK_TIME_NONE
        self.curpos = 0
        self.set_live(False)
        self.set_format(gst.FORMAT_BYTES)

        self.glx_context = GLXContext()

    def do_create(self, offset, size):
        #print (offset, size)
        gst.debug("offset: %r, size:%r" % (offset, size))

        pad = self.get_pad('src')
        caps = pad.get_negotiated_caps()
        increment = int(gst.SECOND / max(1, float(caps[0]['framerate'])))

        if self.pixbuf is None:
            with self.glx_context:
                # XXX: hardcoded width and height
                self.camera.context['w'] = 720
                self.camera.context['h'] = 576
                read = Read(children=[self.camera])
                bc = BufferCamera(720, 576, children=[read])
                bc.render(None)

            self.pixbuf = read.get_pixbuf()

        pixels = self.pixbuf.get_pixels()
        assert len(pixels) == \
            self.camera.context['w'] * self.camera.context['h'] * 3
        buf = gst.Buffer(pixels)
        buf.timestamp = self.curpos
        buf.duration = increment
        self.curpos += buf.duration
        gst.debug("timestamp:%s" % gst.TIME_ARGS(buf.timestamp))
        gst.debug("duration:%s" % gst.TIME_ARGS(buf.duration))
        return (gst.FLOW_OK, buf)

    def do_is_seekable(self):
        return False

gobject.type_register(CameraSource)

