camera.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. """Camera streaming API endpoints for Bambu Lab printers."""
  2. import asyncio
  3. import logging
  4. from collections.abc import AsyncGenerator
  5. from fastapi import APIRouter, Depends, HTTPException, Request
  6. from fastapi.responses import Response, StreamingResponse
  7. from sqlalchemy import select
  8. from sqlalchemy.ext.asyncio import AsyncSession
  9. from backend.app.core.database import get_db
  10. from backend.app.models.printer import Printer
  11. from backend.app.services.camera import (
  12. capture_camera_frame,
  13. get_camera_port,
  14. get_ffmpeg_path,
  15. test_camera_connection,
  16. )
  17. logger = logging.getLogger(__name__)
  18. router = APIRouter(prefix="/printers", tags=["camera"])
  19. # Track active ffmpeg processes for cleanup
  20. _active_streams: dict[str, asyncio.subprocess.Process] = {}
  21. # Store last frame for each printer (for photo capture from active stream)
  22. _last_frames: dict[int, bytes] = {}
  23. def get_buffered_frame(printer_id: int) -> bytes | None:
  24. """Get the last buffered frame for a printer from an active stream.
  25. Returns the JPEG frame data if available, or None if no active stream.
  26. """
  27. return _last_frames.get(printer_id)
  28. async def get_printer_or_404(printer_id: int, db: AsyncSession) -> Printer:
  29. """Get printer by ID or raise 404."""
  30. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  31. printer = result.scalar_one_or_none()
  32. if not printer:
  33. raise HTTPException(status_code=404, detail="Printer not found")
  34. return printer
  35. async def generate_mjpeg_stream(
  36. ip_address: str,
  37. access_code: str,
  38. model: str | None,
  39. fps: int = 10,
  40. stream_id: str | None = None,
  41. disconnect_event: asyncio.Event | None = None,
  42. printer_id: int | None = None,
  43. ) -> AsyncGenerator[bytes, None]:
  44. """Generate MJPEG stream from printer camera using ffmpeg.
  45. This captures frames continuously and yields them in MJPEG format.
  46. """
  47. ffmpeg = get_ffmpeg_path()
  48. if not ffmpeg:
  49. logger.error("ffmpeg not found - camera streaming requires ffmpeg")
  50. yield (b"--frame\r\n" b"Content-Type: text/plain\r\n\r\n" b"Error: ffmpeg not installed\r\n")
  51. return
  52. port = get_camera_port(model)
  53. camera_url = f"rtsps://bblp:{access_code}@{ip_address}:{port}/streaming/live/1"
  54. # ffmpeg command to output MJPEG stream to stdout
  55. # -rtsp_transport tcp: Use TCP for reliability
  56. # -rtsp_flags prefer_tcp: Prefer TCP for RTSP
  57. # -f mjpeg: Output as MJPEG
  58. # -q:v 5: Quality (lower = better, 2-10 is good range)
  59. # -r: Output framerate
  60. cmd = [
  61. ffmpeg,
  62. "-rtsp_transport",
  63. "tcp",
  64. "-rtsp_flags",
  65. "prefer_tcp",
  66. "-i",
  67. camera_url,
  68. "-f",
  69. "mjpeg",
  70. "-q:v",
  71. "5",
  72. "-r",
  73. str(fps),
  74. "-an", # No audio
  75. "-", # Output to stdout
  76. ]
  77. logger.info(f"Starting camera stream for {ip_address} (stream_id={stream_id})")
  78. logger.debug(f"ffmpeg command: {ffmpeg} ... (url hidden)")
  79. process = None
  80. try:
  81. process = await asyncio.create_subprocess_exec(
  82. *cmd,
  83. stdout=asyncio.subprocess.PIPE,
  84. stderr=asyncio.subprocess.PIPE,
  85. )
  86. # Track active process for cleanup
  87. if stream_id:
  88. _active_streams[stream_id] = process
  89. # Give ffmpeg a moment to start and check for immediate failures
  90. await asyncio.sleep(0.5)
  91. if process.returncode is not None:
  92. stderr = await process.stderr.read()
  93. logger.error(f"ffmpeg failed immediately: {stderr.decode()}")
  94. yield (
  95. b"--frame\r\n"
  96. b"Content-Type: text/plain\r\n\r\n"
  97. b"Error: Camera connection failed. Check printer is on and camera is enabled.\r\n"
  98. )
  99. return
  100. # Read JPEG frames from ffmpeg output
  101. # JPEG images start with 0xFFD8 and end with 0xFFD9
  102. buffer = b""
  103. jpeg_start = b"\xff\xd8"
  104. jpeg_end = b"\xff\xd9"
  105. while True:
  106. # Check if client disconnected
  107. if disconnect_event and disconnect_event.is_set():
  108. logger.info(f"Client disconnected, stopping stream {stream_id}")
  109. break
  110. try:
  111. # Read chunk from ffmpeg
  112. chunk = await asyncio.wait_for(process.stdout.read(8192), timeout=10.0)
  113. if not chunk:
  114. logger.warning("Camera stream ended (no more data)")
  115. break
  116. buffer += chunk
  117. # Find complete JPEG frames in buffer
  118. while True:
  119. start_idx = buffer.find(jpeg_start)
  120. if start_idx == -1:
  121. # No start marker, clear buffer up to last 2 bytes
  122. buffer = buffer[-2:] if len(buffer) > 2 else buffer
  123. break
  124. # Trim anything before the start marker
  125. if start_idx > 0:
  126. buffer = buffer[start_idx:]
  127. end_idx = buffer.find(jpeg_end, 2) # Skip first 2 bytes
  128. if end_idx == -1:
  129. # No end marker yet, wait for more data
  130. break
  131. # Extract complete frame
  132. frame = buffer[: end_idx + 2]
  133. buffer = buffer[end_idx + 2 :]
  134. # Save frame to buffer for photo capture
  135. if printer_id is not None:
  136. _last_frames[printer_id] = frame
  137. # Yield frame in MJPEG format
  138. yield (
  139. b"--frame\r\n"
  140. b"Content-Type: image/jpeg\r\n"
  141. b"Content-Length: " + str(len(frame)).encode() + b"\r\n"
  142. b"\r\n" + frame + b"\r\n"
  143. )
  144. except TimeoutError:
  145. logger.warning("Camera stream read timeout")
  146. break
  147. except asyncio.CancelledError:
  148. logger.info(f"Camera stream cancelled (stream_id={stream_id})")
  149. break
  150. except GeneratorExit:
  151. logger.info(f"Camera stream generator exit (stream_id={stream_id})")
  152. break
  153. except FileNotFoundError:
  154. logger.error("ffmpeg not found - camera streaming requires ffmpeg")
  155. yield (b"--frame\r\n" b"Content-Type: text/plain\r\n\r\n" b"Error: ffmpeg not installed\r\n")
  156. except asyncio.CancelledError:
  157. logger.info(f"Camera stream task cancelled (stream_id={stream_id})")
  158. except GeneratorExit:
  159. logger.info(f"Camera stream generator closed (stream_id={stream_id})")
  160. except Exception as e:
  161. logger.exception(f"Camera stream error: {e}")
  162. finally:
  163. # Remove from active streams
  164. if stream_id and stream_id in _active_streams:
  165. del _active_streams[stream_id]
  166. # Clean up frame buffer
  167. if printer_id is not None and printer_id in _last_frames:
  168. del _last_frames[printer_id]
  169. if process and process.returncode is None:
  170. logger.info(f"Terminating ffmpeg process for stream {stream_id}")
  171. try:
  172. process.terminate()
  173. try:
  174. await asyncio.wait_for(process.wait(), timeout=2.0)
  175. except TimeoutError:
  176. logger.warning(f"ffmpeg didn't terminate gracefully, killing (stream_id={stream_id})")
  177. process.kill()
  178. await process.wait()
  179. except ProcessLookupError:
  180. pass # Process already dead
  181. except Exception as e:
  182. logger.warning(f"Error terminating ffmpeg: {e}")
  183. logger.info(f"Camera stream stopped for {ip_address} (stream_id={stream_id})")
  184. @router.get("/{printer_id}/camera/stream")
  185. async def camera_stream(
  186. printer_id: int,
  187. request: Request,
  188. fps: int = 10,
  189. db: AsyncSession = Depends(get_db),
  190. ):
  191. """Stream live video from printer camera as MJPEG.
  192. This endpoint returns a multipart MJPEG stream that can be used directly
  193. in an <img> tag or video player.
  194. Args:
  195. printer_id: Printer ID
  196. fps: Target frames per second (default: 10, max: 30)
  197. """
  198. import uuid
  199. printer = await get_printer_or_404(printer_id, db)
  200. # Validate FPS
  201. fps = min(max(fps, 1), 30)
  202. # Generate unique stream ID for tracking
  203. stream_id = f"{printer_id}-{uuid.uuid4().hex[:8]}"
  204. # Create disconnect event that will be set when client disconnects
  205. disconnect_event = asyncio.Event()
  206. async def stream_with_disconnect_check():
  207. """Wrapper generator that monitors for client disconnect."""
  208. try:
  209. async for chunk in generate_mjpeg_stream(
  210. ip_address=printer.ip_address,
  211. access_code=printer.access_code,
  212. model=printer.model,
  213. fps=fps,
  214. stream_id=stream_id,
  215. disconnect_event=disconnect_event,
  216. printer_id=printer_id,
  217. ):
  218. # Check if client is still connected
  219. if await request.is_disconnected():
  220. logger.info(f"Client disconnected detected for stream {stream_id}")
  221. disconnect_event.set()
  222. break
  223. yield chunk
  224. except asyncio.CancelledError:
  225. logger.info(f"Stream {stream_id} cancelled")
  226. disconnect_event.set()
  227. except GeneratorExit:
  228. logger.info(f"Stream {stream_id} generator closed")
  229. disconnect_event.set()
  230. finally:
  231. disconnect_event.set()
  232. # Give a moment for the inner generator to clean up
  233. await asyncio.sleep(0.1)
  234. return StreamingResponse(
  235. stream_with_disconnect_check(),
  236. media_type="multipart/x-mixed-replace; boundary=frame",
  237. headers={
  238. "Cache-Control": "no-cache, no-store, must-revalidate",
  239. "Pragma": "no-cache",
  240. "Expires": "0",
  241. },
  242. )
  243. @router.api_route("/{printer_id}/camera/stop", methods=["GET", "POST"])
  244. async def stop_camera_stream(printer_id: int):
  245. """Stop all active camera streams for a printer.
  246. This can be called by the frontend when the camera window is closed.
  247. Accepts both GET and POST (POST for sendBeacon compatibility).
  248. """
  249. stopped = 0
  250. to_remove = []
  251. for stream_id, process in list(_active_streams.items()):
  252. if stream_id.startswith(f"{printer_id}-"):
  253. to_remove.append(stream_id)
  254. if process.returncode is None:
  255. try:
  256. process.terminate()
  257. stopped += 1
  258. logger.info(f"Terminated ffmpeg process for stream {stream_id}")
  259. except Exception as e:
  260. logger.warning(f"Error stopping stream {stream_id}: {e}")
  261. for stream_id in to_remove:
  262. _active_streams.pop(stream_id, None)
  263. logger.info(
  264. f"Stopped {stopped} camera stream(s) for printer {printer_id}, active streams remaining: {list(_active_streams.keys())}"
  265. )
  266. return {"stopped": stopped}
  267. @router.get("/{printer_id}/camera/snapshot")
  268. async def camera_snapshot(
  269. printer_id: int,
  270. db: AsyncSession = Depends(get_db),
  271. ):
  272. """Capture a single frame from the printer camera.
  273. Returns a JPEG image.
  274. """
  275. import tempfile
  276. from pathlib import Path
  277. printer = await get_printer_or_404(printer_id, db)
  278. # Create temporary file for the snapshot
  279. with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as f:
  280. temp_path = Path(f.name)
  281. try:
  282. success = await capture_camera_frame(
  283. ip_address=printer.ip_address,
  284. access_code=printer.access_code,
  285. model=printer.model,
  286. output_path=temp_path,
  287. timeout=15,
  288. )
  289. if not success:
  290. raise HTTPException(status_code=503, detail="Failed to capture camera frame. Is the printer powered on?")
  291. # Read and return the image
  292. with open(temp_path, "rb") as f:
  293. image_data = f.read()
  294. return Response(
  295. content=image_data,
  296. media_type="image/jpeg",
  297. headers={
  298. "Cache-Control": "no-cache, no-store, must-revalidate",
  299. "Content-Disposition": f'inline; filename="snapshot_{printer_id}.jpg"',
  300. },
  301. )
  302. finally:
  303. # Clean up temp file
  304. if temp_path.exists():
  305. temp_path.unlink()
  306. @router.get("/{printer_id}/camera/test")
  307. async def test_camera(
  308. printer_id: int,
  309. db: AsyncSession = Depends(get_db),
  310. ):
  311. """Test camera connection for a printer.
  312. Returns success status and any error message.
  313. """
  314. printer = await get_printer_or_404(printer_id, db)
  315. result = await test_camera_connection(
  316. ip_address=printer.ip_address,
  317. access_code=printer.access_code,
  318. model=printer.model,
  319. )
  320. return result