#!/usr/bin/python


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


class Handler(object):
	def __init__(self, mainloop, pipeline):
		self.mainloop = mainloop
		self.pipeline = pipeline

		bus = pipeline.get_bus()
		bus.add_signal_watch()
		bus.connect("message", self.on_message)

	def on_message(self, bus, message):
		if message.type == gst.MESSAGE_EOS:
			self.pipeline.set_state(gst.STATE_NULL)
			self.mainloop.quit()


pipeline = gst.Pipeline("segfault")
mainloop = gobject.MainLoop()


def mkaudiotestsrc(pipeline, **properties):
	elem = gst.element_factory_make("audiotestsrc")
	for name, value in properties.items():
		elem.set_property(name.replace("_", "-"), value)
	pipeline.add(elem)
	return elem


def mkcapsfilter(pipeline, src, caps):
	elem = gst.element_factory_make("capsfilter")
	elem.set_property("caps", caps)
	pipeline.add(elem)
	src.link(elem)
	return elem


def mkqueue(pipeline, src):
	elem = gst.element_factory_make("queue")
	pipeline.add(elem)
	src.link(elem)
	return elem


def mksrc(pipeline):
	snr = mkcapsfilter(pipeline, mkaudiotestsrc(pipeline, samplesperbuffer = 2048, wave = 9), gst.Caps("audio/x-raw-float, channels=2, width=64, rate=2048"))
	return mkqueue(pipeline, snr)


def mkmulti(pipeline):
	nto1 = gst.element_factory_make("input-selector")
	nto1.set_property("select-all", True)
	pipeline.add(nto1)
	for i in range(6):
		mkqueue(pipeline, mksrc(pipeline)).link(nto1)
	return nto1


def mkprogressreport(pipeline, src, name):
	elem = gst.element_factory_make("progressreport", name)
	pipeline.add(elem)
	src.link(elem)
	return elem


def mkfakesink(pipeline, src):
	elem = gst.element_factory_make("fakesink")
	elem.set_property("sync", False)
	elem.set_property("async", False)
	pipeline.add(elem)
	src.link(elem)


mkfakesink(pipeline, mkprogressreport(pipeline, mkmulti(pipeline), "sink"))


handler = Handler(mainloop, pipeline)


pipeline.set_state(gst.STATE_PLAYING)
mainloop.run()
