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())