# requirements.txt: fastapi uvicorn aiortc mediapipe opencv-python ffmpeg-python numpy
# Docker: FROM python:3.11-slim + apt install ffmpeg libopencv-dev
import asyncio
import cv2
import mediapipe as mp
import numpy as np
from aiortc import RTCPeerConnection, RTCSessionDescription, VideoStreamTrack
from aiortc.contrib.media import MediaPlayer
import ffmpeg
from fastapi import FastAPI, WebSocket
from datetime import datetime, timedelta
import time
app = FastAPI()
pcs = set() # Peer connections
LATENCY_BUDGET = timedelta(milliseconds=50) # 50ms E2E
mp_pose = mp.solutions.pose.Pose(static_image_mode=False, model_complexity=1, enable_segmentation=True)
mp_face = mp.solutions.face_detection.FaceDetection(model_selection=0)
class ARVideoTrack(VideoStreamTrack):
def __init__(self, track: VideoStreamTrack):
super().__init__()
self.track = track
def privacy_blur(self, frame: np.ndarray) -> np.ndarray:
"""Privacy: Detect & blur faces."""
rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
results = mp_face.process(rgb_frame)
if results.detections:
for detection in results.detections:
bbox = detection.location_data.relative_bounding_box
h, w, _ = frame.shape
x, y = int(bbox.xmin * w), int(bbox.ymin * h)
w_box, h_box = int(bbox.width * w), int(bbox.height * h)
face = frame[y:y+h_box, x:x+w_box]
blurred = cv2.GaussianBlur(face, (99, 99), 30)
frame[y:y+h_box, x:x+w_box] = blurred
return frame
def pose_ar_overlay(self, frame: np.ndarray) -> np.ndarray:
"""Pose estimation + AR overlay."""
rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
results = mp_pose.process(rgb_frame)
if results.pose_landmarks:
h, w, _ = frame.shape
for idx, landmark in enumerate(results.pose_landmarks.landmark):
x, y = int(landmark.x * w), int(landmark.y * h)
cv2.circle(frame, (x, y), 5, (0, 255, 0), -1) # Green dots for pose
# Add AR: e.g., virtual hat on head (customize)
return frame
async def recv(self):
frame = await self.track.recv()
pts = frame.pts # Presentation timestamp
start = time.time()
img = frame.to_ndarray(format="bgr24")
# Privacy first
img = self.privacy_blur(img)
# Pose + AR (offloaded here)
img = self.pose_ar_overlay(img)
# Latency check
process_time = time.time() - start
if timedelta(seconds=process_time) > LATENCY_BUDGET:
print(f"Latency violation: {process_time*1000:.1f}ms - Dropping frame")
return None # Drop frame
# Adaptive Bitrate: Probe bandwidth (use WebRTC stats)
bitrate = 2000000 # Default 2Mbps; adapt via RTCPeerConnection.getStats()
# In prod: async fetch stats every 1s, scale bitrate 500k-5M
# Encode with FFmpeg (VP9 for efficiency)
out_frame = ffmpeg.input('pipe:', format='rawvideo', pix_fmt='bgr24', s=f'{img.shape[1]}x{img.shape[0]}') \
.output('pipe:', format='vp9', vcodec='libvpx-vp9', b=f'{bitrate}', deadline='realtime', cpu_used=5) \
.run_async(pipe_stdin=True, pipe_stdout=True)
out_frame.stdin.write(img.astype(np.uint8).tobytes())
out_frame.stdin.close()
encoded = out_frame.stdout.read()
new_frame = VideoFrame.from_ndarray(encoded, format="vp9") # Pseudo; use aiortc's frame builder
new_frame.pts = pts + int(process_time * 90000) # 90kHz clock
return new_frame
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
pc = RTCPeerConnection()
pcs.add(pc)
@pc.on("track")
def on_track(track):
if track.kind == "video":
ar_track = ARVideoTrack(track)
pc.addTrack(ar_track)
offer = RTCSessionDescription(sdp=await websocket.receive_text(), type="offer")
await pc.setRemoteDescription(offer)
answer = await pc.createAnswer()
await pc.setLocalDescription(answer)
await websocket.send_text(answer.sdp)
# Adaptive Bitrate Loop (every 1s)
async def abr_loop():
while True:
stats = await pc.getStats()
# Extract available bitrate from 'outbound-rtp_video'
# Adjust FFmpeg bitrate in ARVideoTrack dynamically
await asyncio.sleep(1)
asyncio.create_task(abr_loop())
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8080)