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

Gst.init(None)

pipeline_str = (
    "videotestsrc is-live=true pattern=ball ! video/x-raw,format=I420,width=1280,height=720,framerate=25/1 ! "
    "x264enc tune=zerolatency speed-preset=ultrafast key-int-max=25 ! rtspclientsink name=s "
    "location=rtsp://192.168.1.42:18554/opus-spike-test protocols=tcp "
    "audiotestsrc is-live=true wave=sine freq=440 ! audio/x-raw,rate=48000,channels=2 ! "
    "audioconvert ! voaacenc bitrate=128000 ! s. "
    "audiotestsrc is-live=true wave=sine freq=880 ! audio/x-raw,rate=48000,channels=2 ! "
    "audioconvert ! opusenc bitrate=128000 ! s."
)

pipeline = Gst.parse_launch(pipeline_str)
bus = pipeline.get_bus()
pipeline.set_state(Gst.State.PLAYING)

start = time.time()
while time.time() - start < 3600:
    msg = bus.timed_pop_filtered(500 * Gst.MSECOND, Gst.MessageType.ERROR | Gst.MessageType.EOS | Gst.MessageType.STATE_CHANGED)
    if msg:
        if msg.type == Gst.MessageType.ERROR:
            err, debug = msg.parse_error()
            print(f"ERROR: {err} debug={debug}", flush=True)
            sys.exit(1)
        elif msg.type == Gst.MessageType.EOS:
            print("EOS", flush=True)
            break
        elif msg.type == Gst.MessageType.STATE_CHANGED and msg.src == pipeline:
            old, new, pending = msg.parse_state_changed()
            print(f"pipeline state: {old.value_nick} -> {new.value_nick}", flush=True)

print("ran 12s without fatal error", flush=True)
pipeline.set_state(Gst.State.NULL)
