import pygst
pygst.require("0.10")
import gst
import gobject

class Media:

    def __init__(self, config):

        # set gstreamer basic options
        self.config = config
        self.pipe = ""


    def setup(self, filename, mux, vcodec, vbitrate,\
              fps, acodec, abitrate, width, height, port):

        self.filename = filename
        self.mux = mux
        self.vcodec = vcodec
        self.vbitrate = int(vbitrate)
        self.fps = int(fps)
        self.acodec = acodec
        self.abitrate = int(abitrate)
        self.width = int(width)
        self.height = int(height)

        self.port = int(port)

        ## Pipelines

        #queue ! videoscale ! video/x-raw-yuv,width=240,height=144\
        #! videorate ! ffenc_h263p bitrate=256000 me-method=2 \
        #! rtph263ppay ! udpsink  host=224.0.0.1 port=5000


        #audio/x-raw-int ! queue ! audioconvert ! faac ! rtpmp4gpay\
        #!  udpsink name=upd_audio host=224.0.0.1 port=5002

        self.pipe = "filesrc location=%s ! decodebin name=d ! queue ! videoscale !"\
                    "video/x-raw-yuv,width=(int)%d,height=(int)%d ! ffenc_h263p bitrate=%d"\
                    " me-method=2 ! rtph263ppay ! udpsink host=224.0.0.1 port=%d d. ! "\
                    "queue  ! audioconvert ! faac ! rtpmp4gpay ! udpsink name=udp_audio "\
                    "host=224.0.0.1 port=%d" % (self.filename, self.width, self.height,\
                                                self.vbitrate, self.port, self.port+2)

        #self.pipe = "filesrc location=/tmp/mpg/cpm.mpg ! decodebin ! ffmpegcolorspace ! ximagesink"

        self.pipeline = gst.parse_launch(self.pipe)


    def play(self):

        print "Trying to play pipeline: %s" % self.pipe
        try:
            if (self.pipeline):
                self.pipeline.set_state(gst.STATE_PLAYING)
        except gobject.GError, e:
            print "Error: " + str(e)


    def stop(self):

        print "Trying to stop pipeline: %s" % self.pipe
        try:
            if (self.pipeline):
                self.pipeline.set_state(gst.STATE_NULL)
        except gobject.GError, e:
            print "Error: " + str(e)

