camera.py 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260
  1. """Camera streaming API endpoints for Bambu Lab printers."""
  2. import asyncio
  3. import logging
  4. import subprocess
  5. import sys
  6. from collections.abc import AsyncGenerator
  7. from fastapi import APIRouter, Depends, HTTPException, Request
  8. from fastapi.responses import Response, StreamingResponse
  9. from sqlalchemy import select
  10. from sqlalchemy.ext.asyncio import AsyncSession
  11. from backend.app.core.auth import RequirePermissionIfAuthEnabled
  12. from backend.app.core.database import get_db
  13. from backend.app.core.permissions import Permission
  14. from backend.app.models.printer import Printer
  15. from backend.app.models.user import User
  16. from backend.app.services.camera import (
  17. capture_camera_frame,
  18. generate_chamber_image_stream,
  19. get_camera_port,
  20. get_ffmpeg_path,
  21. is_chamber_image_model,
  22. read_next_chamber_frame,
  23. test_camera_connection,
  24. )
  25. logger = logging.getLogger(__name__)
  26. router = APIRouter(prefix="/printers", tags=["camera"])
  27. # Track active ffmpeg processes for cleanup
  28. _active_streams: dict[str, asyncio.subprocess.Process] = {}
  29. # Track active chamber image connections for cleanup
  30. _active_chamber_streams: dict[str, tuple] = {}
  31. # Store last frame for each printer (for photo capture from active stream)
  32. _last_frames: dict[int, bytes] = {}
  33. # Track last frame timestamp for each printer (for stall detection)
  34. _last_frame_times: dict[int, float] = {}
  35. # Track stream start times for each printer
  36. _stream_start_times: dict[int, float] = {}
  37. # Track active external camera streams by printer ID
  38. _active_external_streams: set[int] = set()
  39. # Track ALL spawned ffmpeg PIDs (persists even if _active_streams entries are removed)
  40. # Maps PID -> spawn timestamp — used by cleanup to find truly orphaned OS processes
  41. _spawned_ffmpeg_pids: dict[int, float] = {}
  42. def get_buffered_frame(printer_id: int) -> bytes | None:
  43. """Get the last buffered frame for a printer from an active stream.
  44. Returns the JPEG frame data if available, or None if no active stream.
  45. """
  46. return _last_frames.get(printer_id)
  47. async def get_printer_or_404(printer_id: int, db: AsyncSession) -> Printer:
  48. """Get printer by ID or raise 404."""
  49. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  50. printer = result.scalar_one_or_none()
  51. if not printer:
  52. raise HTTPException(status_code=404, detail="Printer not found")
  53. return printer
  54. async def generate_chamber_mjpeg_stream(
  55. ip_address: str,
  56. access_code: str,
  57. model: str | None,
  58. fps: int = 5,
  59. stream_id: str | None = None,
  60. disconnect_event: asyncio.Event | None = None,
  61. printer_id: int | None = None,
  62. ) -> AsyncGenerator[bytes, None]:
  63. """Generate MJPEG stream from A1/P1 printer using chamber image protocol.
  64. This connects to port 6000 and reads JPEG frames using the Bambu binary protocol.
  65. """
  66. logger.info("Starting chamber image stream for %s (stream_id=%s, model=%s)", ip_address, stream_id, model)
  67. connection = await generate_chamber_image_stream(ip_address, access_code, fps)
  68. if connection is None:
  69. logger.error("Failed to connect to chamber image stream for %s", ip_address)
  70. yield (
  71. b"--frame\r\n"
  72. b"Content-Type: text/plain\r\n\r\n"
  73. b"Error: Camera connection failed. Check printer is on and camera is enabled.\r\n"
  74. )
  75. return
  76. reader, writer = connection
  77. # Track active connection for cleanup
  78. if stream_id:
  79. _active_chamber_streams[stream_id] = (reader, writer)
  80. try:
  81. frame_interval = 1.0 / fps if fps > 0 else 0.2
  82. last_frame_time = 0.0
  83. while True:
  84. # Check if client disconnected
  85. if disconnect_event and disconnect_event.is_set():
  86. logger.info("Client disconnected, stopping chamber stream %s", stream_id)
  87. break
  88. # Read next frame
  89. frame = await read_next_chamber_frame(reader, timeout=30.0)
  90. if frame is None:
  91. logger.warning("Chamber image stream ended for %s", stream_id)
  92. break
  93. # Save frame to buffer for photo capture and track timestamp
  94. if printer_id is not None:
  95. import time
  96. _last_frames[printer_id] = frame
  97. _last_frame_times[printer_id] = time.time()
  98. # Rate limiting - skip frames if needed to maintain target FPS
  99. current_time = asyncio.get_event_loop().time()
  100. if current_time - last_frame_time < frame_interval:
  101. continue
  102. last_frame_time = current_time
  103. # Yield frame in MJPEG format
  104. yield (
  105. b"--frame\r\n"
  106. b"Content-Type: image/jpeg\r\n"
  107. b"Content-Length: " + str(len(frame)).encode() + b"\r\n"
  108. b"\r\n" + frame + b"\r\n"
  109. )
  110. except asyncio.CancelledError:
  111. logger.info("Chamber image stream cancelled (stream_id=%s)", stream_id)
  112. except GeneratorExit:
  113. logger.info("Chamber image stream generator exit (stream_id=%s)", stream_id)
  114. except Exception as e:
  115. logger.exception("Chamber image stream error: %s", e)
  116. finally:
  117. # Remove from active streams
  118. if stream_id and stream_id in _active_chamber_streams:
  119. del _active_chamber_streams[stream_id]
  120. # Clean up frame buffer and timestamps
  121. if printer_id is not None:
  122. _last_frames.pop(printer_id, None)
  123. _last_frame_times.pop(printer_id, None)
  124. _stream_start_times.pop(printer_id, None)
  125. # Close the connection
  126. try:
  127. writer.close()
  128. await writer.wait_closed()
  129. except OSError:
  130. pass # Connection already closed or broken; cleanup is best-effort
  131. logger.info("Chamber image stream stopped for %s (stream_id=%s)", ip_address, stream_id)
  132. async def generate_rtsp_mjpeg_stream(
  133. ip_address: str,
  134. access_code: str,
  135. model: str | None,
  136. fps: int = 10,
  137. stream_id: str | None = None,
  138. disconnect_event: asyncio.Event | None = None,
  139. printer_id: int | None = None,
  140. ) -> AsyncGenerator[bytes, None]:
  141. """Generate MJPEG stream from printer camera using ffmpeg/RTSP.
  142. This is for X1/H2/P2 models that support RTSP streaming.
  143. """
  144. ffmpeg = get_ffmpeg_path()
  145. if not ffmpeg:
  146. logger.error("ffmpeg not found - camera streaming requires ffmpeg")
  147. yield (b"--frame\r\nContent-Type: text/plain\r\n\r\nError: ffmpeg not installed\r\n")
  148. return
  149. port = get_camera_port(model)
  150. camera_url = f"rtsps://bblp:{access_code}@{ip_address}:{port}/streaming/live/1"
  151. # ffmpeg command to output MJPEG stream to stdout
  152. # -rtsp_transport tcp: Use TCP for reliability
  153. # -rtsp_flags prefer_tcp: Prefer TCP for RTSP
  154. # -timeout: Connection timeout in microseconds (30 seconds)
  155. # -buffer_size: Larger buffer for network jitter
  156. # -max_delay: Maximum demuxing delay
  157. # -f mjpeg: Output as MJPEG
  158. # -q:v 5: Quality (lower = better, 2-10 is good range)
  159. # -r: Output framerate
  160. cmd = [
  161. ffmpeg,
  162. "-rtsp_transport",
  163. "tcp",
  164. "-rtsp_flags",
  165. "prefer_tcp",
  166. "-timeout",
  167. "30000000", # 30 seconds in microseconds
  168. "-buffer_size",
  169. "1024000", # 1MB buffer
  170. "-max_delay",
  171. "500000", # 0.5 seconds max delay
  172. "-i",
  173. camera_url,
  174. "-f",
  175. "mjpeg",
  176. "-q:v",
  177. "5",
  178. "-r",
  179. str(fps),
  180. "-an", # No audio
  181. "-", # Output to stdout
  182. ]
  183. logger.info(
  184. "Starting RTSP camera stream for %s (stream_id=%s, model=%s, fps=%s)", ip_address, stream_id, model, fps
  185. )
  186. logger.debug("ffmpeg command: %s ... (url hidden)", ffmpeg)
  187. process = None
  188. try:
  189. # On Windows, spawn ffmpeg in its own process group so that
  190. # terminate() doesn't broadcast CTRL_C_EVENT to uvicorn (#605).
  191. kwargs: dict = {}
  192. if sys.platform == "win32":
  193. kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP
  194. process = await asyncio.create_subprocess_exec(
  195. *cmd,
  196. stdout=asyncio.subprocess.PIPE,
  197. stderr=asyncio.subprocess.PIPE,
  198. **kwargs,
  199. )
  200. # Track active process for cleanup
  201. if stream_id:
  202. _active_streams[stream_id] = process
  203. import time as _time
  204. _spawned_ffmpeg_pids[process.pid] = _time.time()
  205. # Give ffmpeg a moment to start and check for immediate failures
  206. await asyncio.sleep(0.5)
  207. if process.returncode is not None:
  208. stderr = await process.stderr.read()
  209. logger.error("ffmpeg failed immediately: %s", stderr.decode())
  210. yield (
  211. b"--frame\r\n"
  212. b"Content-Type: text/plain\r\n\r\n"
  213. b"Error: Camera connection failed. Check printer is on and camera is enabled.\r\n"
  214. )
  215. return
  216. # Read JPEG frames from ffmpeg output
  217. # JPEG images start with 0xFFD8 and end with 0xFFD9
  218. buffer = b""
  219. jpeg_start = b"\xff\xd8"
  220. jpeg_end = b"\xff\xd9"
  221. while True:
  222. # Check if client disconnected
  223. if disconnect_event and disconnect_event.is_set():
  224. logger.info("Client disconnected, stopping stream %s", stream_id)
  225. break
  226. try:
  227. # Read chunk from ffmpeg - use longer timeout for network hiccups
  228. chunk = await asyncio.wait_for(process.stdout.read(8192), timeout=30.0)
  229. if not chunk:
  230. logger.warning("Camera stream ended (no more data)")
  231. break
  232. buffer += chunk
  233. # Find complete JPEG frames in buffer
  234. while True:
  235. start_idx = buffer.find(jpeg_start)
  236. if start_idx == -1:
  237. # No start marker, clear buffer up to last 2 bytes
  238. buffer = buffer[-2:] if len(buffer) > 2 else buffer
  239. break
  240. # Trim anything before the start marker
  241. if start_idx > 0:
  242. buffer = buffer[start_idx:]
  243. end_idx = buffer.find(jpeg_end, 2) # Skip first 2 bytes
  244. if end_idx == -1:
  245. # No end marker yet, wait for more data
  246. break
  247. # Extract complete frame
  248. frame = buffer[: end_idx + 2]
  249. buffer = buffer[end_idx + 2 :]
  250. # Save frame to buffer for photo capture and track timestamp
  251. if printer_id is not None:
  252. import time
  253. _last_frames[printer_id] = frame
  254. _last_frame_times[printer_id] = time.time()
  255. # Yield frame in MJPEG format
  256. yield (
  257. b"--frame\r\n"
  258. b"Content-Type: image/jpeg\r\n"
  259. b"Content-Length: " + str(len(frame)).encode() + b"\r\n"
  260. b"\r\n" + frame + b"\r\n"
  261. )
  262. except TimeoutError:
  263. logger.warning("Camera stream read timeout")
  264. break
  265. except asyncio.CancelledError:
  266. logger.info("Camera stream cancelled (stream_id=%s)", stream_id)
  267. break
  268. except GeneratorExit:
  269. logger.info("Camera stream generator exit (stream_id=%s)", stream_id)
  270. break
  271. except FileNotFoundError:
  272. logger.error("ffmpeg not found - camera streaming requires ffmpeg")
  273. yield (b"--frame\r\nContent-Type: text/plain\r\n\r\nError: ffmpeg not installed\r\n")
  274. except asyncio.CancelledError:
  275. logger.info("Camera stream task cancelled (stream_id=%s)", stream_id)
  276. except GeneratorExit:
  277. logger.info("Camera stream generator closed (stream_id=%s)", stream_id)
  278. except Exception as e:
  279. logger.exception("Camera stream error: %s", e)
  280. finally:
  281. # Remove from active streams
  282. if stream_id and stream_id in _active_streams:
  283. del _active_streams[stream_id]
  284. # Clean up frame buffer and timestamps
  285. if printer_id is not None:
  286. _last_frames.pop(printer_id, None)
  287. _last_frame_times.pop(printer_id, None)
  288. _stream_start_times.pop(printer_id, None)
  289. if process and process.returncode is None:
  290. logger.info("Terminating ffmpeg process for stream %s", stream_id)
  291. try:
  292. process.terminate()
  293. try:
  294. await asyncio.wait_for(process.wait(), timeout=2.0)
  295. except TimeoutError:
  296. logger.warning("ffmpeg didn't terminate gracefully, killing (stream_id=%s)", stream_id)
  297. process.kill()
  298. await process.wait()
  299. except ProcessLookupError:
  300. pass # Process already dead
  301. except OSError as e:
  302. logger.warning("Error terminating ffmpeg: %s", e)
  303. logger.info("Camera stream stopped for %s (stream_id=%s)", ip_address, stream_id)
  304. # Remove from PID tracking now that process is confirmed dead
  305. if process:
  306. _spawned_ffmpeg_pids.pop(process.pid, None)
  307. @router.get("/{printer_id}/camera/stream")
  308. async def camera_stream(
  309. printer_id: int,
  310. request: Request,
  311. fps: int = 10,
  312. db: AsyncSession = Depends(get_db),
  313. ):
  314. """Stream live video from printer camera as MJPEG.
  315. This endpoint returns a multipart MJPEG stream that can be used directly
  316. in an <img> tag or video player.
  317. Note: Unauthenticated - loaded via <img> tags which can't send auth headers.
  318. Uses external camera if configured, otherwise uses built-in camera:
  319. - External: MJPEG, RTSP, or HTTP snapshot
  320. - A1/P1: Chamber image protocol (port 6000)
  321. - X1/H2/P2: RTSP via ffmpeg (port 322)
  322. Args:
  323. printer_id: Printer ID
  324. fps: Target frames per second (default: 10, max: 30)
  325. """
  326. import uuid
  327. printer = await get_printer_or_404(printer_id, db)
  328. # Check for external camera first
  329. if printer.external_camera_enabled and printer.external_camera_url:
  330. import time
  331. from backend.app.services.external_camera import generate_mjpeg_stream
  332. # Limit external camera FPS to reduce browser load
  333. fps = min(max(fps, 1), 15)
  334. logger.info(
  335. "Using external camera (%s) for printer %s at %s fps", printer.external_camera_type, printer_id, fps
  336. )
  337. # Track stream start
  338. _stream_start_times[printer_id] = time.time()
  339. _active_external_streams.add(printer_id)
  340. async def external_stream_wrapper():
  341. """Wrap external stream to track start/stop and update frame times."""
  342. frame_interval = 1.0 / fps
  343. last_yield_time = 0.0
  344. try:
  345. async for frame in generate_mjpeg_stream(
  346. printer.external_camera_url, printer.external_camera_type, fps
  347. ):
  348. # Rate limit to prevent overwhelming browser
  349. current_time = time.time()
  350. elapsed = current_time - last_yield_time
  351. if elapsed < frame_interval:
  352. await asyncio.sleep(frame_interval - elapsed)
  353. last_yield_time = time.time()
  354. _last_frame_times[printer_id] = last_yield_time
  355. yield frame
  356. finally:
  357. _active_external_streams.discard(printer_id)
  358. logger.info("External camera stream ended for printer %s", printer_id)
  359. return StreamingResponse(
  360. external_stream_wrapper(),
  361. media_type="multipart/x-mixed-replace; boundary=frame",
  362. headers={
  363. "Cache-Control": "no-cache, no-store, must-revalidate",
  364. "Pragma": "no-cache",
  365. "Expires": "0",
  366. },
  367. )
  368. # Validate FPS - A1/P1 models max out at ~5 FPS
  369. if is_chamber_image_model(printer.model):
  370. fps = min(max(fps, 1), 5)
  371. else:
  372. fps = min(max(fps, 1), 30)
  373. # Generate unique stream ID for tracking
  374. stream_id = f"{printer_id}-{uuid.uuid4().hex[:8]}"
  375. # Create disconnect event that will be set when client disconnects
  376. disconnect_event = asyncio.Event()
  377. # Choose the appropriate stream generator based on model
  378. if is_chamber_image_model(printer.model):
  379. stream_generator = generate_chamber_mjpeg_stream
  380. logger.info("Using chamber image protocol for %s", printer.model)
  381. else:
  382. stream_generator = generate_rtsp_mjpeg_stream
  383. logger.info("Using RTSP protocol for %s", printer.model)
  384. # Track stream start time
  385. import time
  386. _stream_start_times[printer_id] = time.time()
  387. async def _kill_stream_process(sid: str):
  388. """Terminate+kill the ffmpeg process for a stream ID."""
  389. proc = _active_streams.get(sid)
  390. if proc and proc.returncode is None:
  391. try:
  392. proc.terminate()
  393. try:
  394. await asyncio.wait_for(proc.wait(), timeout=2.0)
  395. except TimeoutError:
  396. proc.kill()
  397. await proc.wait()
  398. except (ProcessLookupError, OSError):
  399. pass
  400. async def _monitor_disconnect():
  401. """Background task: poll for client disconnect independently of frame loop."""
  402. try:
  403. while not disconnect_event.is_set():
  404. await asyncio.sleep(2)
  405. if await request.is_disconnected():
  406. logger.info("Disconnect monitor: client gone (stream %s)", stream_id)
  407. disconnect_event.set()
  408. # Kill ffmpeg process (RTSP streams)
  409. await _kill_stream_process(stream_id)
  410. # Close chamber stream connection if applicable
  411. chamber = _active_chamber_streams.get(stream_id)
  412. if chamber:
  413. try:
  414. chamber[1].close()
  415. except OSError:
  416. pass
  417. break
  418. except asyncio.CancelledError:
  419. pass
  420. monitor_task = asyncio.create_task(_monitor_disconnect())
  421. async def stream_with_disconnect_check():
  422. """Wrapper generator that monitors for client disconnect."""
  423. try:
  424. async for chunk in stream_generator(
  425. ip_address=printer.ip_address,
  426. access_code=printer.access_code,
  427. model=printer.model,
  428. fps=fps,
  429. stream_id=stream_id,
  430. disconnect_event=disconnect_event,
  431. printer_id=printer_id,
  432. ):
  433. # Check if client is still connected
  434. if disconnect_event.is_set() or await request.is_disconnected():
  435. logger.info("Client disconnected detected for stream %s", stream_id)
  436. disconnect_event.set()
  437. break
  438. yield chunk
  439. except asyncio.CancelledError:
  440. logger.info("Stream %s cancelled", stream_id)
  441. disconnect_event.set()
  442. except GeneratorExit:
  443. logger.info("Stream %s generator closed", stream_id)
  444. disconnect_event.set()
  445. finally:
  446. disconnect_event.set()
  447. monitor_task.cancel()
  448. # Give a moment for the inner generator to clean up
  449. await asyncio.sleep(0.1)
  450. return StreamingResponse(
  451. stream_with_disconnect_check(),
  452. media_type="multipart/x-mixed-replace; boundary=frame",
  453. headers={
  454. "Cache-Control": "no-cache, no-store, must-revalidate",
  455. "Pragma": "no-cache",
  456. "Expires": "0",
  457. },
  458. )
  459. @router.api_route("/{printer_id}/camera/stop", methods=["GET", "POST"])
  460. async def stop_camera_stream(
  461. printer_id: int,
  462. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  463. ):
  464. """Stop all active camera streams for a printer.
  465. This can be called by the frontend when the camera window is closed.
  466. Accepts both GET and POST (POST for sendBeacon compatibility).
  467. """
  468. stopped = 0
  469. # Stop ffmpeg/RTSP streams
  470. to_remove = []
  471. for stream_id, process in list(_active_streams.items()):
  472. if stream_id.startswith(f"{printer_id}-"):
  473. to_remove.append(stream_id)
  474. if process.returncode is None:
  475. try:
  476. process.terminate()
  477. try:
  478. await asyncio.wait_for(process.wait(), timeout=2.0)
  479. except TimeoutError:
  480. logger.warning("ffmpeg didn't terminate gracefully, killing (stream_id=%s)", stream_id)
  481. process.kill()
  482. await process.wait()
  483. stopped += 1
  484. logger.info("Terminated ffmpeg process for stream %s", stream_id)
  485. except ProcessLookupError:
  486. pass # Process already dead
  487. except OSError as e:
  488. logger.warning("Error stopping stream %s: %s", stream_id, e)
  489. _spawned_ffmpeg_pids.pop(process.pid, None)
  490. for stream_id in to_remove:
  491. _active_streams.pop(stream_id, None)
  492. # Stop chamber image streams
  493. to_remove_chamber = []
  494. for stream_id, (_reader, writer) in list(_active_chamber_streams.items()):
  495. if stream_id.startswith(f"{printer_id}-"):
  496. to_remove_chamber.append(stream_id)
  497. try:
  498. writer.close()
  499. stopped += 1
  500. logger.info("Closed chamber image connection for stream %s", stream_id)
  501. except OSError as e:
  502. logger.warning("Error stopping chamber stream %s: %s", stream_id, e)
  503. for stream_id in to_remove_chamber:
  504. _active_chamber_streams.pop(stream_id, None)
  505. logger.info("Stopped %s camera stream(s) for printer %s", stopped, printer_id)
  506. return {"stopped": stopped}
  507. @router.get("/{printer_id}/camera/snapshot")
  508. async def camera_snapshot(
  509. printer_id: int,
  510. db: AsyncSession = Depends(get_db),
  511. ):
  512. """Capture a single frame from the printer camera.
  513. Returns a JPEG image.
  514. Note: Unauthenticated - loaded via <img> tags which can't send auth headers.
  515. """
  516. import tempfile
  517. from pathlib import Path
  518. printer = await get_printer_or_404(printer_id, db)
  519. # Check for external camera first
  520. if printer.external_camera_enabled and printer.external_camera_url:
  521. from backend.app.services.external_camera import capture_frame
  522. frame_data = await capture_frame(printer.external_camera_url, printer.external_camera_type, timeout=15)
  523. if not frame_data:
  524. raise HTTPException(
  525. status_code=503,
  526. detail="Failed to capture frame from external camera.",
  527. )
  528. return Response(
  529. content=frame_data,
  530. media_type="image/jpeg",
  531. headers={
  532. "Cache-Control": "no-cache, no-store, must-revalidate",
  533. "Content-Disposition": f'inline; filename="snapshot_{printer_id}.jpg"',
  534. },
  535. )
  536. # Create temporary file for the snapshot
  537. with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as f:
  538. temp_path = Path(f.name)
  539. try:
  540. success = await capture_camera_frame(
  541. ip_address=printer.ip_address,
  542. access_code=printer.access_code,
  543. model=printer.model,
  544. output_path=temp_path,
  545. timeout=15,
  546. )
  547. if not success:
  548. raise HTTPException(
  549. status_code=503,
  550. detail="Failed to capture camera frame. Ensure printer is on and camera is enabled.",
  551. )
  552. # Read and return the image
  553. with open(temp_path, "rb") as f:
  554. image_data = f.read()
  555. return Response(
  556. content=image_data,
  557. media_type="image/jpeg",
  558. headers={
  559. "Cache-Control": "no-cache, no-store, must-revalidate",
  560. "Content-Disposition": f'inline; filename="snapshot_{printer_id}.jpg"',
  561. },
  562. )
  563. finally:
  564. # Clean up temp file
  565. if temp_path.exists():
  566. temp_path.unlink()
  567. @router.get("/{printer_id}/camera/test")
  568. async def test_camera(
  569. printer_id: int,
  570. db: AsyncSession = Depends(get_db),
  571. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  572. ):
  573. """Test camera connection for a printer.
  574. Returns success status and any error message.
  575. """
  576. printer = await get_printer_or_404(printer_id, db)
  577. result = await test_camera_connection(
  578. ip_address=printer.ip_address,
  579. access_code=printer.access_code,
  580. model=printer.model,
  581. )
  582. return result
  583. @router.get("/{printer_id}/camera/status")
  584. async def camera_status(
  585. printer_id: int,
  586. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  587. ):
  588. """Get the status of an active camera stream.
  589. Returns whether a stream is active and when the last frame was received.
  590. Used by the frontend to detect stalled streams and auto-reconnect.
  591. """
  592. import time
  593. # Check if there's an active stream for this printer
  594. has_active_stream = False
  595. # Check external camera streams
  596. if printer_id in _active_external_streams:
  597. has_active_stream = True
  598. # Check ffmpeg/RTSP streams
  599. if not has_active_stream:
  600. for stream_id in _active_streams:
  601. if stream_id.startswith(f"{printer_id}-"):
  602. process = _active_streams[stream_id]
  603. if process.returncode is None:
  604. has_active_stream = True
  605. break
  606. # Check chamber image streams
  607. if not has_active_stream:
  608. for stream_id in _active_chamber_streams:
  609. if stream_id.startswith(f"{printer_id}-"):
  610. has_active_stream = True
  611. break
  612. # Get timing information
  613. current_time = time.time()
  614. last_frame_time = _last_frame_times.get(printer_id)
  615. stream_start_time = _stream_start_times.get(printer_id)
  616. # Calculate seconds since last frame
  617. seconds_since_frame = None
  618. if last_frame_time is not None:
  619. seconds_since_frame = current_time - last_frame_time
  620. # Calculate stream uptime
  621. stream_uptime = None
  622. if stream_start_time is not None:
  623. stream_uptime = current_time - stream_start_time
  624. return {
  625. "active": has_active_stream,
  626. "has_frames": printer_id in _last_frames,
  627. "seconds_since_frame": seconds_since_frame,
  628. "stream_uptime": stream_uptime,
  629. # Consider stalled if no frame for more than 10 seconds after stream started
  630. "stalled": (
  631. has_active_stream
  632. and stream_uptime is not None
  633. and stream_uptime > 5 # Give 5 seconds for stream to start
  634. and (seconds_since_frame is None or seconds_since_frame > 10)
  635. ),
  636. }
  637. @router.post("/{printer_id}/camera/external/test")
  638. async def test_external_camera(
  639. printer_id: int,
  640. url: str,
  641. camera_type: str,
  642. db: AsyncSession = Depends(get_db),
  643. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  644. ):
  645. """Test external camera connection.
  646. Args:
  647. printer_id: Printer ID (for authorization)
  648. url: Camera URL or USB device path to test
  649. camera_type: Camera type ("mjpeg", "rtsp", "snapshot", "usb")
  650. Returns:
  651. Dict with {success: bool, error?: str, resolution?: str}
  652. """
  653. # Verify printer exists (for authorization)
  654. await get_printer_or_404(printer_id, db)
  655. from backend.app.services.external_camera import test_connection
  656. return await test_connection(url, camera_type)
  657. @router.get("/{printer_id}/camera/check-plate")
  658. async def check_plate_empty(
  659. printer_id: int,
  660. plate_type: str | None = None,
  661. use_external: bool = False,
  662. include_debug_image: bool = False,
  663. db: AsyncSession = Depends(get_db),
  664. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  665. ):
  666. """Check if the build plate is empty using camera vision.
  667. Uses calibration-based difference detection - compares current frame
  668. to a reference image of the empty plate.
  669. IMPORTANT: Chamber light must be ON for reliable detection.
  670. Args:
  671. printer_id: Printer ID
  672. plate_type: Type of build plate (e.g., "High Temp Plate") for calibration lookup
  673. use_external: If True, prefer external camera over built-in
  674. include_debug_image: If True, return URL to annotated debug image
  675. Returns:
  676. Dict with detection results:
  677. - is_empty: bool - Whether plate appears empty
  678. - confidence: float - Confidence level (0.0 to 1.0)
  679. - difference_percent: float - How different from calibration reference
  680. - message: str - Human-readable result message
  681. - needs_calibration: bool - True if calibration is required
  682. - light_warning: bool - True if chamber light is off
  683. """
  684. from backend.app.services.plate_detection import (
  685. check_plate_empty as do_check,
  686. is_plate_detection_available,
  687. )
  688. from backend.app.services.printer_manager import printer_manager
  689. # Check printer exists first (before OpenCV check)
  690. printer = await get_printer_or_404(printer_id, db)
  691. if not is_plate_detection_available():
  692. raise HTTPException(
  693. status_code=503,
  694. detail="Plate detection not available. Install opencv-python-headless to enable.",
  695. )
  696. # Check chamber light status
  697. light_warning = False
  698. state = printer_manager.get_status(printer_id)
  699. if state and not state.chamber_light:
  700. light_warning = True
  701. from backend.app.services.plate_detection import PlateDetector
  702. # Build ROI tuple from printer settings if available
  703. roi = None
  704. if all(
  705. [
  706. printer.plate_detection_roi_x is not None,
  707. printer.plate_detection_roi_y is not None,
  708. printer.plate_detection_roi_w is not None,
  709. printer.plate_detection_roi_h is not None,
  710. ]
  711. ):
  712. roi = (
  713. printer.plate_detection_roi_x,
  714. printer.plate_detection_roi_y,
  715. printer.plate_detection_roi_w,
  716. printer.plate_detection_roi_h,
  717. )
  718. result = await do_check(
  719. printer_id=printer.id,
  720. ip_address=printer.ip_address,
  721. access_code=printer.access_code,
  722. model=printer.model,
  723. plate_type=plate_type,
  724. include_debug_image=include_debug_image,
  725. external_camera_url=printer.external_camera_url if printer.external_camera_enabled else None,
  726. external_camera_type=printer.external_camera_type if printer.external_camera_enabled else None,
  727. use_external=use_external,
  728. roi=roi,
  729. )
  730. # Get reference count for the response
  731. detector = PlateDetector()
  732. ref_count = detector.get_calibration_count(printer.id)
  733. response = result.to_dict()
  734. response["light_warning"] = light_warning
  735. response["reference_count"] = ref_count
  736. response["max_references"] = detector.MAX_REFERENCES
  737. # Include current ROI in response
  738. if roi:
  739. response["roi"] = {"x": roi[0], "y": roi[1], "w": roi[2], "h": roi[3]}
  740. else:
  741. # Return default ROI
  742. response["roi"] = {"x": 0.15, "y": 0.35, "w": 0.70, "h": 0.55}
  743. # If debug image requested and available, encode as base64 data URL
  744. if include_debug_image and result.debug_image:
  745. import base64
  746. b64_image = base64.b64encode(result.debug_image).decode("utf-8")
  747. response["debug_image_url"] = f"data:image/jpeg;base64,{b64_image}"
  748. return response
  749. @router.post("/{printer_id}/camera/plate-detection/calibrate")
  750. async def calibrate_plate_detection(
  751. printer_id: int,
  752. label: str | None = None,
  753. use_external: bool = False,
  754. db: AsyncSession = Depends(get_db),
  755. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  756. ):
  757. """Calibrate plate detection by capturing a reference image of the empty plate.
  758. The plate MUST be empty when calling this endpoint. The captured image
  759. will be used as the reference for future detection comparisons.
  760. Supports up to 5 reference images per printer. When adding a 6th, the oldest
  761. is automatically removed.
  762. IMPORTANT: Chamber light should be ON for calibration.
  763. Args:
  764. printer_id: Printer ID
  765. label: Optional label for this reference (e.g., "High Temp Plate", "Wham Bam")
  766. use_external: If True, prefer external camera over built-in
  767. Returns:
  768. Dict with:
  769. - success: bool - Whether calibration succeeded
  770. - message: str - Status message
  771. - index: int - The reference slot used (0-4)
  772. """
  773. from backend.app.services.plate_detection import (
  774. calibrate_plate,
  775. is_plate_detection_available,
  776. )
  777. from backend.app.services.printer_manager import printer_manager
  778. # Check printer exists first (before OpenCV check)
  779. printer = await get_printer_or_404(printer_id, db)
  780. if not is_plate_detection_available():
  781. raise HTTPException(
  782. status_code=503,
  783. detail="Plate detection not available. Install opencv-python-headless to enable.",
  784. )
  785. # Check chamber light - warn but don't block
  786. state = printer_manager.get_status(printer_id)
  787. light_warning = state and not state.chamber_light
  788. success, message, index = await calibrate_plate(
  789. printer_id=printer.id,
  790. ip_address=printer.ip_address,
  791. access_code=printer.access_code,
  792. model=printer.model,
  793. label=label,
  794. external_camera_url=printer.external_camera_url if printer.external_camera_enabled else None,
  795. external_camera_type=printer.external_camera_type if printer.external_camera_enabled else None,
  796. use_external=use_external,
  797. )
  798. if light_warning and success:
  799. message += " (Warning: Chamber light was off)"
  800. return {"success": success, "message": message, "index": index}
  801. @router.delete("/{printer_id}/camera/plate-detection/calibrate")
  802. async def delete_plate_calibration(
  803. printer_id: int,
  804. plate_type: str | None = None,
  805. db: AsyncSession = Depends(get_db),
  806. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  807. ):
  808. """Delete the plate detection calibration for a printer and plate type.
  809. Args:
  810. printer_id: Printer ID
  811. plate_type: Type of build plate (if None, deletes legacy non-plate-specific calibration)
  812. Returns:
  813. Dict with:
  814. - success: bool - Whether deletion succeeded
  815. - message: str - Status message
  816. """
  817. from backend.app.services.plate_detection import (
  818. delete_calibration,
  819. is_plate_detection_available,
  820. )
  821. # Verify printer exists first (before OpenCV check)
  822. await get_printer_or_404(printer_id, db)
  823. if not is_plate_detection_available():
  824. raise HTTPException(
  825. status_code=503,
  826. detail="Plate detection not available. Install opencv-python-headless to enable.",
  827. )
  828. deleted = delete_calibration(printer_id, plate_type)
  829. plate_msg = f" for '{plate_type}'" if plate_type else ""
  830. return {
  831. "success": deleted,
  832. "message": f"Calibration deleted{plate_msg}" if deleted else f"No calibration found{plate_msg}",
  833. }
  834. @router.get("/{printer_id}/camera/plate-detection/status")
  835. async def get_plate_detection_status(
  836. printer_id: int,
  837. plate_type: str | None = None,
  838. db: AsyncSession = Depends(get_db),
  839. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  840. ):
  841. """Check plate detection status for a printer and plate type.
  842. Returns:
  843. Dict with:
  844. - available: bool - Whether OpenCV is installed
  845. - calibrated: bool - Whether printer has calibration for this plate type
  846. - plate_type: str - The plate type queried
  847. - chamber_light: bool - Whether chamber light is on
  848. - message: str - Status message
  849. """
  850. from backend.app.services.plate_detection import (
  851. get_calibration_status,
  852. is_plate_detection_available,
  853. )
  854. from backend.app.services.printer_manager import printer_manager
  855. # Verify printer exists first (before OpenCV check)
  856. await get_printer_or_404(printer_id, db)
  857. if not is_plate_detection_available():
  858. return {
  859. "available": False,
  860. "calibrated": False,
  861. "plate_type": plate_type,
  862. "chamber_light": False,
  863. "message": "OpenCV not installed",
  864. }
  865. # Get chamber light status
  866. state = printer_manager.get_status(printer_id)
  867. chamber_light = state.chamber_light if state else False
  868. status = get_calibration_status(printer_id, plate_type)
  869. status["chamber_light"] = chamber_light
  870. return status
  871. @router.get("/{printer_id}/camera/plate-detection/references")
  872. async def get_plate_references(
  873. printer_id: int,
  874. db: AsyncSession = Depends(get_db),
  875. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  876. ):
  877. """Get all calibration references for a printer with metadata.
  878. Returns list of references with index, label, timestamp, and thumbnail URL.
  879. """
  880. from backend.app.services.plate_detection import PlateDetector, is_plate_detection_available
  881. # Verify printer exists first (before OpenCV check)
  882. await get_printer_or_404(printer_id, db)
  883. if not is_plate_detection_available():
  884. raise HTTPException(503, "Plate detection not available")
  885. detector = PlateDetector()
  886. references = detector.get_references(printer_id)
  887. # Add thumbnail URLs
  888. for ref in references:
  889. ref["thumbnail_url"] = (
  890. f"/api/v1/printers/{printer_id}/camera/plate-detection/references/{ref['index']}/thumbnail"
  891. )
  892. return {
  893. "references": references,
  894. "max_references": detector.MAX_REFERENCES,
  895. }
  896. @router.get("/{printer_id}/camera/plate-detection/references/{index}/thumbnail")
  897. async def get_reference_thumbnail(
  898. printer_id: int,
  899. index: int,
  900. db: AsyncSession = Depends(get_db),
  901. ):
  902. """Get thumbnail image for a calibration reference.
  903. Note: Unauthenticated - loaded via <img> tags which can't send auth headers.
  904. """
  905. from fastapi.responses import Response
  906. from backend.app.services.plate_detection import PlateDetector, is_plate_detection_available
  907. # Verify printer exists first (before OpenCV check)
  908. await get_printer_or_404(printer_id, db)
  909. if not is_plate_detection_available():
  910. raise HTTPException(503, "Plate detection not available")
  911. detector = PlateDetector()
  912. thumbnail = detector.get_reference_thumbnail(printer_id, index)
  913. if thumbnail is None:
  914. raise HTTPException(404, "Reference not found")
  915. return Response(content=thumbnail, media_type="image/jpeg")
  916. @router.put("/{printer_id}/camera/plate-detection/references/{index}")
  917. async def update_reference_label(
  918. printer_id: int,
  919. index: int,
  920. label: str,
  921. db: AsyncSession = Depends(get_db),
  922. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  923. ):
  924. """Update the label for a calibration reference."""
  925. from backend.app.services.plate_detection import PlateDetector, is_plate_detection_available
  926. # Verify printer exists first (before OpenCV check)
  927. await get_printer_or_404(printer_id, db)
  928. if not is_plate_detection_available():
  929. raise HTTPException(503, "Plate detection not available")
  930. detector = PlateDetector()
  931. success = detector.update_reference_label(printer_id, index, label)
  932. if not success:
  933. raise HTTPException(404, "Reference not found")
  934. return {"success": True, "index": index, "label": label}
  935. @router.delete("/{printer_id}/camera/plate-detection/references/{index}")
  936. async def delete_reference(
  937. printer_id: int,
  938. index: int,
  939. db: AsyncSession = Depends(get_db),
  940. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  941. ):
  942. """Delete a specific calibration reference."""
  943. from backend.app.services.plate_detection import PlateDetector, is_plate_detection_available
  944. # Verify printer exists first (before OpenCV check)
  945. await get_printer_or_404(printer_id, db)
  946. if not is_plate_detection_available():
  947. raise HTTPException(503, "Plate detection not available")
  948. detector = PlateDetector()
  949. success = detector.delete_reference(printer_id, index)
  950. if not success:
  951. raise HTTPException(404, "Reference not found")
  952. return {"success": True, "message": "Reference deleted"}
  953. def _scan_bambu_ffmpeg_pids() -> list[int]:
  954. """Scan /proc for ffmpeg processes with Bambu RTSP URLs.
  955. These are definitely ours — no other software connects to rtsps://bblp:.
  956. This catches orphans that survive app restarts and are not in any tracking dict.
  957. """
  958. import os
  959. pids = []
  960. try:
  961. for entry in os.listdir("/proc"):
  962. if not entry.isdigit():
  963. continue
  964. try:
  965. with open(f"/proc/{entry}/cmdline", "rb") as f:
  966. cmdline = f.read()
  967. if b"ffmpeg" in cmdline and b"rtsps://bblp:" in cmdline:
  968. pids.append(int(entry))
  969. except (OSError, PermissionError, ValueError):
  970. continue
  971. except OSError:
  972. pass
  973. return pids
  974. async def cleanup_orphaned_streams():
  975. """Clean up orphaned ffmpeg processes and stale stream entries.
  976. Called periodically from the background task loop in main.py.
  977. Three-layer cleanup:
  978. 1. /proc scan — finds ALL Bambu ffmpeg processes on the system, even those
  979. from previous app sessions. This is the nuclear safety net.
  980. 2. _spawned_ffmpeg_pids — tracks PIDs spawned this session, catches orphans
  981. that were removed from _active_streams but not killed.
  982. 3. _active_streams — kills stale entries with no recent frames.
  983. """
  984. import os
  985. import signal
  986. import time
  987. cleaned = 0
  988. now = time.time()
  989. # Collect PIDs that are legitimately in-use (active stream, process alive)
  990. active_pids = {proc.pid for proc in _active_streams.values() if proc.returncode is None}
  991. # 1. /proc scan — catch ALL orphaned Bambu ffmpeg processes on the system.
  992. # Any ffmpeg with rtsps://bblp: that is NOT in an active stream is orphaned.
  993. for pid in _scan_bambu_ffmpeg_pids():
  994. if pid in active_pids:
  995. continue
  996. logger.info("Killing orphaned ffmpeg process found via /proc (pid=%d)", pid)
  997. try:
  998. os.kill(pid, signal.SIGKILL)
  999. except (ProcessLookupError, OSError):
  1000. pass
  1001. _spawned_ffmpeg_pids.pop(pid, None)
  1002. cleaned += 1
  1003. # 2. Clean up _spawned_ffmpeg_pids entries for dead processes
  1004. for pid in list(_spawned_ffmpeg_pids):
  1005. try:
  1006. os.kill(pid, 0) # existence check
  1007. except (ProcessLookupError, OSError):
  1008. _spawned_ffmpeg_pids.pop(pid, None)
  1009. # 3. Clean up _active_streams entries with dead processes
  1010. dead_streams = [sid for sid, proc in _active_streams.items() if proc.returncode is not None]
  1011. for sid in dead_streams:
  1012. proc = _active_streams.pop(sid, None)
  1013. if proc:
  1014. _spawned_ffmpeg_pids.pop(proc.pid, None)
  1015. cleaned += 1
  1016. # 4. Kill stale active streams (alive but no frames for >60s)
  1017. for sid, proc in list(_active_streams.items()):
  1018. if proc.returncode is not None:
  1019. continue
  1020. try:
  1021. printer_id = int(sid.split("-", 1)[0])
  1022. except (ValueError, IndexError):
  1023. continue
  1024. start_time = _stream_start_times.get(printer_id, now)
  1025. last_frame = _last_frame_times.get(printer_id, start_time)
  1026. if now - start_time > 120 and now - last_frame > 60:
  1027. logger.info("Killing stale ffmpeg stream %s (no frames for %.0fs)", sid, now - last_frame)
  1028. try:
  1029. proc.kill()
  1030. await proc.wait()
  1031. except (ProcessLookupError, OSError):
  1032. pass
  1033. _active_streams.pop(sid, None)
  1034. _spawned_ffmpeg_pids.pop(proc.pid, None)
  1035. cleaned += 1
  1036. # 4. Clean stale chamber stream entries
  1037. dead_chamber = [sid for sid, (_reader, writer) in _active_chamber_streams.items() if writer.is_closing()]
  1038. for sid in dead_chamber:
  1039. _active_chamber_streams.pop(sid, None)
  1040. cleaned += 1
  1041. if cleaned:
  1042. logger.info("Cleaned up %d orphaned camera stream(s)", cleaned)