import gi
import sys

gi.require_version('Gst', '1.0')
from gi.repository import Gst, GObject, GLib

def on_message(bus, message):
    m_type = message.type
    if m_type == Gst.MessageType.EOS:
        print("End of Stream (EOS).")
        loop.quit()
    elif m_type == Gst.MessageType.ERROR:
        err, debug = message.parse_error()
        print(f"Error: {err.message}")
        print(f"Debugging info: {debug}")
        loop.quit()
    return True

# Initialize GStreamer
Gst.init(None)

# Build the pipeline string
# videotestsrc: generates a test video pattern
# autovideosink: an automatic sink that displays video in a window
pipeline_string = "videotestsrc ! autovideosink"

# Create the pipeline from the string
pipeline = Gst.parse_launch(pipeline_string)

if not pipeline:
    print("Failed to create pipeline.")
    sys.exit(1)

# Get the bus and set up the message handler
bus = pipeline.get_bus()
bus.add_signal_watch()
bus.connect("message", on_message)

# Create and run the GLib main loop
loop = GLib.MainLoop()

print("Starting video pipeline. Close the window or press Ctrl+C to stop.")
pipeline.set_state(Gst.State.PLAYING)

try:
    loop.run()
except KeyboardInterrupt:
    print("Stopping pipeline.")
finally:
    # Clean up
    pipeline.set_state(Gst.State.NULL)
    bus.remove_signal_watch()
    print("Pipeline stopped.")
