#!/usr/bin/env python
#
# GStreamer python bindings
# Copyright (C) 2002 David I. Lehn <dlehn@users.sourceforge.net>
#               2004 Johan Dahlin  <johan@gnome.org>
#		2005 Benjamin Otte <otte@gnome.org>
#
# filesrc.py: implements a file source element completely in python
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library 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
# Library General Public License for more details.
#
# You should have received a copy of the GNU Library General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.

import sys
import gobject
import gst

def srcpad_get(pad):
    self = pad.get_parent()
    if self.fd == None:
	raise AttributeError, 'file is not open'
    data = self.fd.read(self.blocksize)
    buf = gst.Buffer(data)
    if buf:
	return buf
    else:
	self.set_eos()
	return gst.Event(gst.EVENT_EOS)

class FileSource(gst.Element):
    __gproperties__ = {
	'location': (gobject.TYPE_STRING, 'location', 'filename to play', None, gobject.PARAM_READWRITE),
	'blocksize': (gobject.TYPE_INT, 'blocksize', 'size of buffers', 1, 1024*1024, 4096, gobject.PARAM_READWRITE)
    }
    __gsttemplates__ = (
	gst.PadTemplate ("src", gst.PAD_SRC, gst.PAD_ALWAYS, "ANY")
    )
    __gstdetails__ = ("Python File Source", "Source/File", "read contents from a file", 
	"David I. Lehn <dlehn@users.sourceforge.net>, Johan Dahlin  <johan@gnome.org>, Benjamin Otte <otte@gnome.org>")
    blocksize = 4096
    fd = None
    location = None
    def __init__(self):
        gst.Element.__init__(self)
        pad = gst.Pad(self.__gsttemplates__)
        pad.set_get_function(srcpad_get)
        self.add_pad(pad)
            
    def do_get_property(self, spec):
        if spec.name == 'location':
            return self.location
        if spec.name == 'blocksize':
            return self.blocksize

    def do_set_property(self, spec, value):
        if spec.name == 'location':
            self.location = value
        if spec.name == 'blocksize':
            self.blocksize = value
            
    def do_change_state(self):
	#FIXME: somehow support switch statements and GST_STATE_TRANSITION
	if self.fd == None and self.get_state() > gst.STATE_NULL:
	    try:
		self.fd = open(self.location, 'r')
	    except:
		return gst.STATE_FAILURE
	if self.get_state() == gst.STATE_NULL:
	    self.fd = None
	return gst.Element.do_change_state (self)

gobject.type_register(FileSource)
gst.element_register(FileSource, "pysrc")
