Py.Cafe

kawrei/

websockets-video-streaming

Real-Time Video Streaming with WebSockets and OpenCV

DocsPricing
  • app.py
  • forsaken3.mp4
  • requirements.txt
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import asyncio
import websockets
import cv2
import base64
import json

# CONFIGURATION — update these:
WEBSOCKET_URI = "ws://bucketeernation.com/cameraws"   # Your websocket URI
VIDEO_SOURCE   = "forsaken3.mp4"             # e.g. "0" for default webcam or "/path/video.mp4"
FPS            = 30                              # Desired frame rate

# Compute delay between frames
DELAY = 1.0 / FPS

async def send_frames():
    # open the video source (0 for webcam, or path to video file)
    cap = cv2.VideoCapture(int(VIDEO_SOURCE) if VIDEO_SOURCE.isdigit() else VIDEO_SOURCE)
    if not cap.isOpened():
        print(f"[Error] Cannot open video source: {VIDEO_SOURCE}")
        return

    async with websockets.connect(WEBSOCKET_URI) as ws:
        while True:
            ret, frame = cap.read()
            if not ret:
                # Restart video file if it ends
                cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
                continue

            # 1) Resize to 320×180
            resized = cv2.resize(frame, (320, 180))

            # 2) Encode as JPEG (8-bit, 3-channel) in memory
            #    The default JPEG quality (cv2.IMWRITE_JPEG_QUALITY) is 95; adjust if needed.
            success, jpg_buffer = cv2.imencode('.jpg', resized, [int(cv2.IMWRITE_JPEG_QUALITY), 95])
            if not success:
                continue

            # 3) Base64-encode the JPEG bytes
            jpg_bytes = jpg_buffer.tobytes()
            b64_str = base64.b64encode(jpg_bytes).decode('utf-8')

            # 4) Build and send JSON payload
            payload = {
                "method": "camera-frame",
                "pixels": b64_str
            }
            print(await ws.send(json.dumps(payload)))
            # 5) Wait to match target FPS
            await asyncio.sleep(DELAY)

    cap.release()

if __name__ == "__main__":
    asyncio.run(send_frames())