#!/usr/bin/env python
# This is a reworked version gstreamer example 2 from Jono Bacon's Python and
# Gstreamer primer:
# http://www.jonobacon.org/2006/08/28/getting-started-with-gstreamer-with-python
#
# It uses Gstreamer 1.0, GTK3, and replaces alsa with pulse for audio output
# Info on porting python scripts to GStreamer 1.0 can be found here:
# https://wiki.ubuntu.com/Novacut/GStreamer1.0

import gi, signal
gi.require_version('Gtk', '3.0')
gi.require_version('Gst', '1.0')
from gi.repository import Gtk, Gst

class Main:
    def __init__(self):

        # Create gui bits and bobs

        self.wTree = Gtk.Builder()
        self.wTree.add_from_file("example2.glade")

        signals = {
            "on_play_clicked" : self.OnPlay,
            "on_stop_clicked" : self.OnStop,
            "on_quit_clicked" : self.OnQuit,
        }

        self.wTree.connect_signals(signals)

        # Create GStreamer bits and bobs

        # Initiate the pipeline
        Gst.init(None)
        self.pipeline = Gst.Pipeline()

        # Add an audiotestsrc element to the pipeline
        self.audiotestsrc = Gst.ElementFactory.make("audiotestsrc", "audio")
        self.audiotestsrc.set_property("freq", 800)
        self.pipeline.add(self.audiotestsrc)

        # Add a pulsesink element to the pipeline
        self.pulsesink = Gst.ElementFactory.make("pulsesink", "sink")
        self.pipeline.add(self.pulsesink)

        # Link the two elements together
        self.audiotestsrc.link(self.pulsesink)

        # Summon the window and connect the window's close button to Quit
        self.window = self.wTree.get_object("mainwindow")
        self.window.connect("delete-event", Gtk.main_quit)
        self.window.show_all()


    def OnPlay(self, widget):
        print("play")
        self.pipeline.set_state(Gst.State.PLAYING)

    def OnStop(self, widget):
        print("stop")
        self.pipeline.set_state(Gst.State.READY)

    def OnQuit(self, widget):
        print("quit")
        Gtk.main_quit()

    # Workaround to get Ctrl+C to terminate from command line
    # ref: https://bugzilla.gnome.org/show_bug.cgi?id=622084#c12
    signal.signal(signal.SIGINT, signal.SIG_DFL)

start = Main()
Gtk.main()
