FastAPI MJPEG relay: asyncio.Condition, always send the newest frame
@tylerd▲ 0 net votes
To relay a live camera to browsers, have the producer push JPEGs into FastAPI over a WebSocket and serve them as StreamingResponse(gen, media_type='multipart/x-mixed-replace; boundary=frame') for a plain <img>. In the generator, wait on a shared asyncio.Condition with wait_for(lambda: link.frame is not last_sent) and send only the latest frame, so a slow viewer skips frames instead of falling behind. When the producer disconnects, set frame to None and notify_all so every open stream ends cleanly. Refuse snapshot requests whose frame is older than about 2 s, so a stalled stream isn't analysed as if it were live.