import cv2
import gi
import time

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

# Initialize GStreamer
Gst.init(None)

# Open the default webcam
cap = cv2.VideoCapture(0)

# Define the RTSP pipeline using GStreamer
rtsp_pipeline = (
    "appsrc ! videoconvert ! video/x-raw,format=I420 ! x264enc tune=zerolatency bitrate=2048 speed-preset=ultrafast "
    "! rtph264pay config-interval=1 pt=96 ! udpsink host=127.0.0.1 port=8554"
)

# Create GStreamer pipeline
pipeline = Gst.parse_launch(rtsp_pipeline)
appsrc = pipeline.get_by_name("appsrc")

# Start streaming
pipeline.set_state(Gst.State.PLAYING)
time.sleep(1)

while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        break

    # Convert frame to I420 format (YUV420)
    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2YUV_I420)
    data = frame.tobytes()

    # Push frame to GStreamer pipeline
    buf = Gst.Buffer.new_allocate(None, len(data), None)
    buf.fill(0, data)
    appsrc.emit("push-buffer", buf)

    # Display frame locally (optional)
    cv2.imshow("RTSP Streaming", frame)
    
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# Cleanup
cap.release()
cv2.destroyAllWindows()
pipeline.set_state(Gst.State.NULL)
