camera.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  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. generate_chamber_image_stream,
  14. get_camera_port,
  15. get_ffmpeg_path,
  16. is_chamber_image_model,
  17. read_next_chamber_frame,
  18. test_camera_connection,
  19. )
  20. logger = logging.getLogger(__name__)
  21. router = APIRouter(prefix="/printers", tags=["camera"])
  22. # Track active ffmpeg processes for cleanup
  23. _active_streams: dict[str, asyncio.subprocess.Process] = {}
  24. # Track active chamber image connections for cleanup
  25. _active_chamber_streams: dict[str, tuple] = {}
  26. # Store last frame for each printer (for photo capture from active stream)
  27. _last_frames: dict[int, bytes] = {}
  28. def get_buffered_frame(printer_id: int) -> bytes | None:
  29. """Get the last buffered frame for a printer from an active stream.
  30. Returns the JPEG frame data if available, or None if no active stream.
  31. """
  32. return _last_frames.get(printer_id)
  33. async def get_printer_or_404(printer_id: int, db: AsyncSession) -> Printer:
  34. """Get printer by ID or raise 404."""
  35. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  36. printer = result.scalar_one_or_none()
  37. if not printer:
  38. raise HTTPException(status_code=404, detail="Printer not found")
  39. return printer
  40. async def generate_chamber_mjpeg_stream(
  41. ip_address: str,
  42. access_code: str,
  43. model: str | None,
  44. fps: int = 5,
  45. stream_id: str | None = None,
  46. disconnect_event: asyncio.Event | None = None,
  47. printer_id: int | None = None,
  48. ) -> AsyncGenerator[bytes, None]:
  49. """Generate MJPEG stream from A1/P1 printer using chamber image protocol.
  50. This connects to port 6000 and reads JPEG frames using the Bambu binary protocol.
  51. """
  52. logger.info(f"Starting chamber image stream for {ip_address} (stream_id={stream_id}, model={model})")
  53. connection = await generate_chamber_image_stream(ip_address, access_code, fps)
  54. if connection is None:
  55. logger.error(f"Failed to connect to chamber image stream for {ip_address}")
  56. yield (
  57. b"--frame\r\n"
  58. b"Content-Type: text/plain\r\n\r\n"
  59. b"Error: Camera connection failed. Check printer is on and camera is enabled.\r\n"
  60. )
  61. return
  62. reader, writer = connection
  63. # Track active connection for cleanup
  64. if stream_id:
  65. _active_chamber_streams[stream_id] = (reader, writer)
  66. try:
  67. frame_interval = 1.0 / fps if fps > 0 else 0.2
  68. last_frame_time = 0.0
  69. while True:
  70. # Check if client disconnected
  71. if disconnect_event and disconnect_event.is_set():
  72. logger.info(f"Client disconnected, stopping chamber stream {stream_id}")
  73. break
  74. # Read next frame
  75. frame = await read_next_chamber_frame(reader, timeout=30.0)
  76. if frame is None:
  77. logger.warning(f"Chamber image stream ended for {stream_id}")
  78. break
  79. # Save frame to buffer for photo capture
  80. if printer_id is not None:
  81. _last_frames[printer_id] = frame
  82. # Rate limiting - skip frames if needed to maintain target FPS
  83. current_time = asyncio.get_event_loop().time()
  84. if current_time - last_frame_time < frame_interval:
  85. continue
  86. last_frame_time = current_time
  87. # Yield frame in MJPEG format
  88. yield (
  89. b"--frame\r\n"
  90. b"Content-Type: image/jpeg\r\n"
  91. b"Content-Length: " + str(len(frame)).encode() + b"\r\n"
  92. b"\r\n" + frame + b"\r\n"
  93. )
  94. except asyncio.CancelledError:
  95. logger.info(f"Chamber image stream cancelled (stream_id={stream_id})")
  96. except GeneratorExit:
  97. logger.info(f"Chamber image stream generator exit (stream_id={stream_id})")
  98. except Exception as e:
  99. logger.exception(f"Chamber image stream error: {e}")
  100. finally:
  101. # Remove from active streams
  102. if stream_id and stream_id in _active_chamber_streams:
  103. del _active_chamber_streams[stream_id]
  104. # Clean up frame buffer
  105. if printer_id is not None and printer_id in _last_frames:
  106. del _last_frames[printer_id]
  107. # Close the connection
  108. try:
  109. writer.close()
  110. await writer.wait_closed()
  111. except Exception:
  112. pass
  113. logger.info(f"Chamber image stream stopped for {ip_address} (stream_id={stream_id})")
  114. async def generate_rtsp_mjpeg_stream(
  115. ip_address: str,
  116. access_code: str,
  117. model: str | None,
  118. fps: int = 10,
  119. stream_id: str | None = None,
  120. disconnect_event: asyncio.Event | None = None,
  121. printer_id: int | None = None,
  122. ) -> AsyncGenerator[bytes, None]:
  123. """Generate MJPEG stream from printer camera using ffmpeg/RTSP.
  124. This is for X1/H2/P2 models that support RTSP streaming.
  125. """
  126. ffmpeg = get_ffmpeg_path()
  127. if not ffmpeg:
  128. logger.error("ffmpeg not found - camera streaming requires ffmpeg")
  129. yield (b"--frame\r\n" b"Content-Type: text/plain\r\n\r\n" b"Error: ffmpeg not installed\r\n")
  130. return
  131. port = get_camera_port(model)
  132. camera_url = f"rtsps://bblp:{access_code}@{ip_address}:{port}/streaming/live/1"
  133. # ffmpeg command to output MJPEG stream to stdout
  134. # -rtsp_transport tcp: Use TCP for reliability
  135. # -rtsp_flags prefer_tcp: Prefer TCP for RTSP
  136. # -timeout: Connection timeout in microseconds (30 seconds)
  137. # -buffer_size: Larger buffer for network jitter
  138. # -max_delay: Maximum demuxing delay
  139. # -f mjpeg: Output as MJPEG
  140. # -q:v 5: Quality (lower = better, 2-10 is good range)
  141. # -r: Output framerate
  142. cmd = [
  143. ffmpeg,
  144. "-rtsp_transport",
  145. "tcp",
  146. "-rtsp_flags",
  147. "prefer_tcp",
  148. "-timeout",
  149. "30000000", # 30 seconds in microseconds
  150. "-buffer_size",
  151. "1024000", # 1MB buffer
  152. "-max_delay",
  153. "500000", # 0.5 seconds max delay
  154. "-i",
  155. camera_url,
  156. "-f",
  157. "mjpeg",
  158. "-q:v",
  159. "5",
  160. "-r",
  161. str(fps),
  162. "-an", # No audio
  163. "-", # Output to stdout
  164. ]
  165. logger.info(f"Starting RTSP camera stream for {ip_address} (stream_id={stream_id}, model={model}, fps={fps})")
  166. logger.debug(f"ffmpeg command: {ffmpeg} ... (url hidden)")
  167. process = None
  168. try:
  169. process = await asyncio.create_subprocess_exec(
  170. *cmd,
  171. stdout=asyncio.subprocess.PIPE,
  172. stderr=asyncio.subprocess.PIPE,
  173. )
  174. # Track active process for cleanup
  175. if stream_id:
  176. _active_streams[stream_id] = process
  177. # Give ffmpeg a moment to start and check for immediate failures
  178. await asyncio.sleep(0.5)
  179. if process.returncode is not None:
  180. stderr = await process.stderr.read()
  181. logger.error(f"ffmpeg failed immediately: {stderr.decode()}")
  182. yield (
  183. b"--frame\r\n"
  184. b"Content-Type: text/plain\r\n\r\n"
  185. b"Error: Camera connection failed. Check printer is on and camera is enabled.\r\n"
  186. )
  187. return
  188. # Read JPEG frames from ffmpeg output
  189. # JPEG images start with 0xFFD8 and end with 0xFFD9
  190. buffer = b""
  191. jpeg_start = b"\xff\xd8"
  192. jpeg_end = b"\xff\xd9"
  193. while True:
  194. # Check if client disconnected
  195. if disconnect_event and disconnect_event.is_set():
  196. logger.info(f"Client disconnected, stopping stream {stream_id}")
  197. break
  198. try:
  199. # Read chunk from ffmpeg - use longer timeout for network hiccups
  200. chunk = await asyncio.wait_for(process.stdout.read(8192), timeout=30.0)
  201. if not chunk:
  202. logger.warning("Camera stream ended (no more data)")
  203. break
  204. buffer += chunk
  205. # Find complete JPEG frames in buffer
  206. while True:
  207. start_idx = buffer.find(jpeg_start)
  208. if start_idx == -1:
  209. # No start marker, clear buffer up to last 2 bytes
  210. buffer = buffer[-2:] if len(buffer) > 2 else buffer
  211. break
  212. # Trim anything before the start marker
  213. if start_idx > 0:
  214. buffer = buffer[start_idx:]
  215. end_idx = buffer.find(jpeg_end, 2) # Skip first 2 bytes
  216. if end_idx == -1:
  217. # No end marker yet, wait for more data
  218. break
  219. # Extract complete frame
  220. frame = buffer[: end_idx + 2]
  221. buffer = buffer[end_idx + 2 :]
  222. # Save frame to buffer for photo capture
  223. if printer_id is not None:
  224. _last_frames[printer_id] = frame
  225. # Yield frame in MJPEG format
  226. yield (
  227. b"--frame\r\n"
  228. b"Content-Type: image/jpeg\r\n"
  229. b"Content-Length: " + str(len(frame)).encode() + b"\r\n"
  230. b"\r\n" + frame + b"\r\n"
  231. )
  232. except TimeoutError:
  233. logger.warning("Camera stream read timeout")
  234. break
  235. except asyncio.CancelledError:
  236. logger.info(f"Camera stream cancelled (stream_id={stream_id})")
  237. break
  238. except GeneratorExit:
  239. logger.info(f"Camera stream generator exit (stream_id={stream_id})")
  240. break
  241. except FileNotFoundError:
  242. logger.error("ffmpeg not found - camera streaming requires ffmpeg")
  243. yield (b"--frame\r\n" b"Content-Type: text/plain\r\n\r\n" b"Error: ffmpeg not installed\r\n")
  244. except asyncio.CancelledError:
  245. logger.info(f"Camera stream task cancelled (stream_id={stream_id})")
  246. except GeneratorExit:
  247. logger.info(f"Camera stream generator closed (stream_id={stream_id})")
  248. except Exception as e:
  249. logger.exception(f"Camera stream error: {e}")
  250. finally:
  251. # Remove from active streams
  252. if stream_id and stream_id in _active_streams:
  253. del _active_streams[stream_id]
  254. # Clean up frame buffer
  255. if printer_id is not None and printer_id in _last_frames:
  256. del _last_frames[printer_id]
  257. if process and process.returncode is None:
  258. logger.info(f"Terminating ffmpeg process for stream {stream_id}")
  259. try:
  260. process.terminate()
  261. try:
  262. await asyncio.wait_for(process.wait(), timeout=2.0)
  263. except TimeoutError:
  264. logger.warning(f"ffmpeg didn't terminate gracefully, killing (stream_id={stream_id})")
  265. process.kill()
  266. await process.wait()
  267. except ProcessLookupError:
  268. pass # Process already dead
  269. except Exception as e:
  270. logger.warning(f"Error terminating ffmpeg: {e}")
  271. logger.info(f"Camera stream stopped for {ip_address} (stream_id={stream_id})")
  272. @router.get("/{printer_id}/camera/stream")
  273. async def camera_stream(
  274. printer_id: int,
  275. request: Request,
  276. fps: int = 10,
  277. db: AsyncSession = Depends(get_db),
  278. ):
  279. """Stream live video from printer camera as MJPEG.
  280. This endpoint returns a multipart MJPEG stream that can be used directly
  281. in an <img> tag or video player.
  282. Uses the appropriate protocol based on printer model:
  283. - A1/P1: Chamber image protocol (port 6000)
  284. - X1/H2/P2: RTSP via ffmpeg (port 322)
  285. Args:
  286. printer_id: Printer ID
  287. fps: Target frames per second (default: 10, max: 30)
  288. """
  289. import uuid
  290. printer = await get_printer_or_404(printer_id, db)
  291. # Validate FPS - A1/P1 models max out at ~5 FPS
  292. if is_chamber_image_model(printer.model):
  293. fps = min(max(fps, 1), 5)
  294. else:
  295. fps = min(max(fps, 1), 30)
  296. # Generate unique stream ID for tracking
  297. stream_id = f"{printer_id}-{uuid.uuid4().hex[:8]}"
  298. # Create disconnect event that will be set when client disconnects
  299. disconnect_event = asyncio.Event()
  300. # Choose the appropriate stream generator based on model
  301. if is_chamber_image_model(printer.model):
  302. stream_generator = generate_chamber_mjpeg_stream
  303. logger.info(f"Using chamber image protocol for {printer.model}")
  304. else:
  305. stream_generator = generate_rtsp_mjpeg_stream
  306. logger.info(f"Using RTSP protocol for {printer.model}")
  307. async def stream_with_disconnect_check():
  308. """Wrapper generator that monitors for client disconnect."""
  309. try:
  310. async for chunk in stream_generator(
  311. ip_address=printer.ip_address,
  312. access_code=printer.access_code,
  313. model=printer.model,
  314. fps=fps,
  315. stream_id=stream_id,
  316. disconnect_event=disconnect_event,
  317. printer_id=printer_id,
  318. ):
  319. # Check if client is still connected
  320. if await request.is_disconnected():
  321. logger.info(f"Client disconnected detected for stream {stream_id}")
  322. disconnect_event.set()
  323. break
  324. yield chunk
  325. except asyncio.CancelledError:
  326. logger.info(f"Stream {stream_id} cancelled")
  327. disconnect_event.set()
  328. except GeneratorExit:
  329. logger.info(f"Stream {stream_id} generator closed")
  330. disconnect_event.set()
  331. finally:
  332. disconnect_event.set()
  333. # Give a moment for the inner generator to clean up
  334. await asyncio.sleep(0.1)
  335. return StreamingResponse(
  336. stream_with_disconnect_check(),
  337. media_type="multipart/x-mixed-replace; boundary=frame",
  338. headers={
  339. "Cache-Control": "no-cache, no-store, must-revalidate",
  340. "Pragma": "no-cache",
  341. "Expires": "0",
  342. },
  343. )
  344. @router.api_route("/{printer_id}/camera/stop", methods=["GET", "POST"])
  345. async def stop_camera_stream(printer_id: int):
  346. """Stop all active camera streams for a printer.
  347. This can be called by the frontend when the camera window is closed.
  348. Accepts both GET and POST (POST for sendBeacon compatibility).
  349. """
  350. stopped = 0
  351. # Stop ffmpeg/RTSP streams
  352. to_remove = []
  353. for stream_id, process in list(_active_streams.items()):
  354. if stream_id.startswith(f"{printer_id}-"):
  355. to_remove.append(stream_id)
  356. if process.returncode is None:
  357. try:
  358. process.terminate()
  359. stopped += 1
  360. logger.info(f"Terminated ffmpeg process for stream {stream_id}")
  361. except Exception as e:
  362. logger.warning(f"Error stopping stream {stream_id}: {e}")
  363. for stream_id in to_remove:
  364. _active_streams.pop(stream_id, None)
  365. # Stop chamber image streams
  366. to_remove_chamber = []
  367. for stream_id, (_reader, writer) in list(_active_chamber_streams.items()):
  368. if stream_id.startswith(f"{printer_id}-"):
  369. to_remove_chamber.append(stream_id)
  370. try:
  371. writer.close()
  372. stopped += 1
  373. logger.info(f"Closed chamber image connection for stream {stream_id}")
  374. except Exception as e:
  375. logger.warning(f"Error stopping chamber stream {stream_id}: {e}")
  376. for stream_id in to_remove_chamber:
  377. _active_chamber_streams.pop(stream_id, None)
  378. logger.info(f"Stopped {stopped} camera stream(s) for printer {printer_id}")
  379. return {"stopped": stopped}
  380. @router.get("/{printer_id}/camera/snapshot")
  381. async def camera_snapshot(
  382. printer_id: int,
  383. db: AsyncSession = Depends(get_db),
  384. ):
  385. """Capture a single frame from the printer camera.
  386. Returns a JPEG image.
  387. """
  388. import tempfile
  389. from pathlib import Path
  390. printer = await get_printer_or_404(printer_id, db)
  391. # Create temporary file for the snapshot
  392. with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as f:
  393. temp_path = Path(f.name)
  394. try:
  395. success = await capture_camera_frame(
  396. ip_address=printer.ip_address,
  397. access_code=printer.access_code,
  398. model=printer.model,
  399. output_path=temp_path,
  400. timeout=15,
  401. )
  402. if not success:
  403. raise HTTPException(
  404. status_code=503,
  405. detail="Failed to capture camera frame. Ensure printer is on and camera is enabled.",
  406. )
  407. # Read and return the image
  408. with open(temp_path, "rb") as f:
  409. image_data = f.read()
  410. return Response(
  411. content=image_data,
  412. media_type="image/jpeg",
  413. headers={
  414. "Cache-Control": "no-cache, no-store, must-revalidate",
  415. "Content-Disposition": f'inline; filename="snapshot_{printer_id}.jpg"',
  416. },
  417. )
  418. finally:
  419. # Clean up temp file
  420. if temp_path.exists():
  421. temp_path.unlink()
  422. @router.get("/{printer_id}/camera/test")
  423. async def test_camera(
  424. printer_id: int,
  425. db: AsyncSession = Depends(get_db),
  426. ):
  427. """Test camera connection for a printer.
  428. Returns success status and any error message.
  429. """
  430. printer = await get_printer_or_404(printer_id, db)
  431. result = await test_camera_connection(
  432. ip_address=printer.ip_address,
  433. access_code=printer.access_code,
  434. model=printer.model,
  435. )
  436. return result