import cv2
import subprocess
import os
import numpy as np
import time

import os
os.environ["DISPLAY"] = ":0"

def simple_gstreamer_to_opencv():
    """最简单的GStreamer到OpenCV方案"""
    pipe_path = "/tmp/simple_video_pipe"
    
    # 清理旧管道
    if os.path.exists(pipe_path):
        os.remove(pipe_path)
    
    # 创建管道
    os.mkfifo(pipe_path)
    print("命名管道已创建")
    
    # 启动GStreamer（后台运行）
    gst_cmd = (
        "exec gst-launch-1.0 udpsrc address=230.1.1.1 port=1720 multicast-iface=enx00e0986113a6 "
        "! application/x-rtp, media=video, encoding-name=H264 ! rtph264depay ! h264parse "
        "! avdec_h264 ! videoconvert ! video/x-raw,format=BGR,width=1280,height=720 "
        "! filesink location=" + pipe_path + " > /dev/null 2>&1 &"
    )
    
    print("启动GStreamer...")
    os.system(gst_cmd)
    
    # 等待启动
    time.sleep(3)
    
    try:
        print("开始读取视频...")
        width, height = 1280, 720
        frame_size = width * height * 3
        
        with open(pipe_path, 'rb') as pipe:
            frame_count = 0
            while True:
                # 读取一帧
                frame_data = pipe.read(frame_size)
                
                if len(frame_data) == frame_size:
                    # 转换为图像并显示
                    frame = np.frombuffer(frame_data, dtype=np.uint8).reshape((height, width, 3))
                    cv2.imshow('Video', frame)
                    frame_count += 1
                    
                    if frame_count % 30 == 0:
                        print(f"显示第 {frame_count} 帧")
                
                # 检查退出
                if cv2.waitKey(1) & 0xFF == ord('q'):
                    break
                    
    except Exception as e:
        print(f"错误: {e}")
    finally:
        # 清理
        os.system("pkill -f gst-launch")
        if os.path.exists(pipe_path):
            os.remove(pipe_path)
        cv2.destroyAllWindows()
        print("程序结束")

if __name__ == "__main__":
    simple_gstreamer_to_opencv()
