import gi
import sys

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

def play_kiosk_video():
    Gst.init(None)

    VIDEO_PATH = "file:///root/python/vid.mp4"

    SINK_STR = (
        "videoconvert ! "
        "video/x-raw,format=BGRx ! "
        "kmssink driver-name=mxsfb-drm connector-id=37 plane-id=31 can-scale=false" )

    # Create the playbin element
    pipeline = Gst.ElementFactory.make("playbin", "player")
    pipeline.set_property("uri", VIDEO_PATH)
                
    # Set the custom video sink
    video_sink = Gst.parse_bin_from_description(SINK_STR, True)
    pipeline.set_property("video-sink", video_sink)
                                
    # Set audio to fakesink (prevents errors if no audio hardware is found)
    audio_sink = Gst.ElementFactory.make("fakesink", "audio-fake")
    pipeline.set_property("audio-sink", audio_sink)

    # --- LOOPING LOGIC ---
    bus = pipeline.get_bus()
    bus.add_signal_watch()

    def on_message(bus, msg):
        t = msg.type
        if t == Gst.MessageType.EOS:
            print("End of video. Looping...")
            pipeline.seek_simple(Gst.Format.TIME, Gst.SeekFlags.FLUSH | Gst.SeekFlags.KEY_UNIT, 0)
        elif t == Gst.MessageType.ERROR:
            err, debug = msg.parse_error()
            print(f"Error: {err}")
            loop.quit()
        return True

    bus.connect("message", on_message)

    # Start playback
    print(f"Starting playback: {VIDEO_PATH}")
    pipeline.set_state(Gst.State.PLAYING)

    loop = GLib.MainLoop()
    try:
        loop.run()
    except KeyboardInterrupt:
        print("\nStopping player...")
    finally:
        pipeline.set_state(Gst.State.NULL)

if __name__ == "__main__":
    play_kiosk_video()
