camera.py 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456
  1. """Camera streaming API endpoints for Bambu Lab printers."""
  2. import asyncio
  3. import logging
  4. import os
  5. import subprocess
  6. import sys
  7. from collections.abc import AsyncGenerator
  8. from fastapi import APIRouter, Depends, HTTPException, Request
  9. from fastapi.responses import Response, StreamingResponse
  10. from sqlalchemy import select
  11. from sqlalchemy.ext.asyncio import AsyncSession
  12. from backend.app.core.auth import (
  13. RequireCameraStreamTokenIfAuthEnabled,
  14. RequirePermissionIfAuthEnabled,
  15. create_camera_stream_token,
  16. )
  17. from backend.app.core.database import get_db
  18. from backend.app.core.permissions import Permission
  19. from backend.app.models.printer import Printer
  20. from backend.app.models.user import User
  21. from backend.app.services.camera import (
  22. capture_camera_frame,
  23. create_tls_proxy,
  24. generate_chamber_image_stream,
  25. get_camera_port,
  26. get_ffmpeg_path,
  27. is_chamber_image_model,
  28. read_next_chamber_frame,
  29. test_camera_connection,
  30. )
  31. from backend.app.services.camera_fanout import (
  32. MjpegBroadcaster,
  33. get_or_create_broadcaster,
  34. iter_subscriber,
  35. shutdown_broadcaster,
  36. )
  37. logger = logging.getLogger(__name__)
  38. router = APIRouter(prefix="/printers", tags=["camera"])
  39. # Track active ffmpeg processes for cleanup
  40. _active_streams: dict[str, asyncio.subprocess.Process] = {}
  41. # Track active chamber image connections for cleanup
  42. _active_chamber_streams: dict[str, tuple] = {}
  43. # Store last frame for each printer (for photo capture from active stream)
  44. _last_frames: dict[int, bytes] = {}
  45. # Track last frame timestamp for each printer (for stall detection)
  46. _last_frame_times: dict[int, float] = {}
  47. # Track stream start times for each printer
  48. _stream_start_times: dict[int, float] = {}
  49. # Track active external camera streams by printer ID
  50. _active_external_streams: set[int] = set()
  51. # Track ALL spawned ffmpeg PIDs (persists even if _active_streams entries are removed)
  52. # Maps PID -> spawn timestamp — used by cleanup to find truly orphaned OS processes
  53. _spawned_ffmpeg_pids: dict[int, float] = {}
  54. # Track disconnect events per stream_id — allows stop endpoint and cleanup
  55. # to signal generators to stop reconnecting instead of just killing the process
  56. _disconnect_events: dict[str, asyncio.Event] = {}
  57. # Track last frame time per stream_id (not just per printer_id) for stale detection
  58. _stream_last_frame_times: dict[str, float] = {}
  59. def get_buffered_frame(printer_id: int) -> bytes | None:
  60. """Get the last buffered frame for a printer from an active stream.
  61. Returns the JPEG frame data if available, or None if no active stream.
  62. """
  63. return _last_frames.get(printer_id)
  64. async def get_printer_or_404(printer_id: int, db: AsyncSession) -> Printer:
  65. """Get printer by ID or raise 404."""
  66. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  67. printer = result.scalar_one_or_none()
  68. if not printer:
  69. raise HTTPException(status_code=404, detail="Printer not found")
  70. return printer
  71. async def generate_chamber_mjpeg_stream(
  72. ip_address: str,
  73. access_code: str,
  74. model: str | None,
  75. fps: int = 5,
  76. stream_id: str | None = None,
  77. disconnect_event: asyncio.Event | None = None,
  78. printer_id: int | None = None,
  79. ) -> AsyncGenerator[bytes, None]:
  80. """Generate MJPEG stream from A1/P1 printer using chamber image protocol.
  81. This connects to port 6000 and reads JPEG frames using the Bambu binary protocol.
  82. """
  83. logger.info("Starting chamber image stream for %s (stream_id=%s, model=%s)", ip_address, stream_id, model)
  84. # Register disconnect event so stop endpoint can signal us
  85. if stream_id and disconnect_event:
  86. _disconnect_events[stream_id] = disconnect_event
  87. connection = await generate_chamber_image_stream(ip_address, access_code, fps)
  88. if connection is None:
  89. logger.error("Failed to connect to chamber image stream for %s", ip_address)
  90. yield (
  91. b"--frame\r\n"
  92. b"Content-Type: text/plain\r\n\r\n"
  93. b"Error: Camera connection failed. Check printer is on and camera is enabled.\r\n"
  94. )
  95. return
  96. reader, writer = connection
  97. # Track active connection for cleanup
  98. if stream_id:
  99. _active_chamber_streams[stream_id] = (reader, writer)
  100. try:
  101. frame_interval = 1.0 / fps if fps > 0 else 0.2
  102. last_frame_time = 0.0
  103. while True:
  104. # Check if client disconnected
  105. if disconnect_event and disconnect_event.is_set():
  106. logger.info("Client disconnected, stopping chamber stream %s", stream_id)
  107. break
  108. # Read next frame
  109. frame = await read_next_chamber_frame(reader, timeout=30.0)
  110. if frame is None:
  111. logger.warning("Chamber image stream ended for %s", stream_id)
  112. break
  113. # Save frame to buffer for photo capture and track timestamp
  114. if printer_id is not None:
  115. import time
  116. _last_frames[printer_id] = frame
  117. _last_frame_times[printer_id] = time.time()
  118. # Rate limiting - skip frames if needed to maintain target FPS
  119. current_time = asyncio.get_event_loop().time()
  120. if current_time - last_frame_time < frame_interval:
  121. continue
  122. last_frame_time = current_time
  123. # Yield frame in MJPEG format
  124. yield (
  125. b"--frame\r\n"
  126. b"Content-Type: image/jpeg\r\n"
  127. b"Content-Length: " + str(len(frame)).encode() + b"\r\n"
  128. b"\r\n" + frame + b"\r\n"
  129. )
  130. except asyncio.CancelledError:
  131. logger.info("Chamber image stream cancelled (stream_id=%s)", stream_id)
  132. except GeneratorExit:
  133. logger.info("Chamber image stream generator exit (stream_id=%s)", stream_id)
  134. except Exception as e:
  135. logger.exception("Chamber image stream error: %s", e)
  136. finally:
  137. # Remove from active streams and disconnect events
  138. if stream_id:
  139. _active_chamber_streams.pop(stream_id, None)
  140. _disconnect_events.pop(stream_id, None)
  141. _stream_last_frame_times.pop(stream_id, None)
  142. # Clean up frame buffer and timestamps
  143. if printer_id is not None:
  144. _last_frames.pop(printer_id, None)
  145. _last_frame_times.pop(printer_id, None)
  146. _stream_start_times.pop(printer_id, None)
  147. # Close the connection
  148. try:
  149. writer.close()
  150. await writer.wait_closed()
  151. except OSError:
  152. pass # Connection already closed or broken; cleanup is best-effort
  153. logger.info("Chamber image stream stopped for %s (stream_id=%s)", ip_address, stream_id)
  154. async def _terminate_ffmpeg(process: asyncio.subprocess.Process, stream_id: str | None = None) -> None:
  155. """Terminate an ffmpeg process gracefully, then kill if needed."""
  156. if process.returncode is not None:
  157. return # Already dead
  158. try:
  159. process.terminate()
  160. try:
  161. await asyncio.wait_for(process.wait(), timeout=2.0)
  162. except TimeoutError:
  163. logger.warning("ffmpeg didn't terminate gracefully, killing (stream_id=%s)", stream_id)
  164. process.kill()
  165. await process.wait()
  166. except ProcessLookupError:
  167. pass # Already dead
  168. except OSError as e:
  169. logger.warning("Error terminating ffmpeg: %s", e)
  170. _spawned_ffmpeg_pids.pop(process.pid, None)
  171. def _summarize_ffmpeg_stderr(text: str | None) -> str:
  172. """Strip ffmpeg's boilerplate banner and keep only actionable lines.
  173. ffmpeg prints ~20 lines of version/build/configuration/lib headers before
  174. any actual error message. Logging the full banner on every retry floods
  175. the log (hundreds of lines per failed stream). This filter drops the
  176. banner and caps output at the last 10 meaningful lines.
  177. """
  178. if not text:
  179. return ""
  180. banner_prefixes = (
  181. "ffmpeg version ",
  182. " built with ",
  183. " configuration:",
  184. " libavutil ",
  185. " libavcodec ",
  186. " libavformat ",
  187. " libavdevice ",
  188. " libavfilter ",
  189. " libswscale ",
  190. " libswresample ",
  191. " libpostproc ",
  192. )
  193. meaningful = [ln for ln in text.splitlines() if ln.strip() and not ln.startswith(banner_prefixes)]
  194. return "\n".join(meaningful[-10:])
  195. async def _read_ffmpeg_stderr(process: asyncio.subprocess.Process) -> str | None:
  196. """Read ffmpeg stderr for diagnostics (best-effort, non-blocking).
  197. Returns the stderr content with ffmpeg's boilerplate banner stripped,
  198. so log output stays focused on the actual error.
  199. """
  200. if not process or not process.stderr:
  201. return None
  202. try:
  203. data = await asyncio.wait_for(process.stderr.read(), timeout=2.0)
  204. if not data:
  205. return None
  206. return _summarize_ffmpeg_stderr(data.decode(errors="replace")) or None
  207. except (TimeoutError, Exception):
  208. return None
  209. # Max consecutive RTSP reconnections before giving up.
  210. # Some printer firmwares (notably P2S) drop RTSP sessions after a few seconds,
  211. # so we transparently respawn ffmpeg to keep the MJPEG stream alive.
  212. _RTSP_MAX_RECONNECTS = 30
  213. _RTSP_RECONNECT_DELAY = 0.2 # seconds between respawns
  214. async def generate_rtsp_mjpeg_stream(
  215. ip_address: str,
  216. access_code: str,
  217. model: str | None,
  218. fps: int = 10,
  219. stream_id: str | None = None,
  220. disconnect_event: asyncio.Event | None = None,
  221. printer_id: int | None = None,
  222. ) -> AsyncGenerator[bytes, None]:
  223. """Generate MJPEG stream from printer camera using ffmpeg/RTSP.
  224. This is for X1/H2/P2 models that support RTSP streaming.
  225. Auto-reconnects when the printer drops the RTSP session (common on P2S).
  226. """
  227. ffmpeg = get_ffmpeg_path()
  228. if not ffmpeg:
  229. logger.error("ffmpeg not found - camera streaming requires ffmpeg")
  230. yield (b"--frame\r\nContent-Type: text/plain\r\n\r\nError: ffmpeg not installed\r\n")
  231. return
  232. port = get_camera_port(model)
  233. # Use a local TLS proxy so Python's OpenSSL handles TLS instead of
  234. # ffmpeg's GnuTLS. This fixes P2S (and potentially other models)
  235. # dropping the RTSP session after a few seconds due to GnuTLS's
  236. # hardened Debian defaults rejecting TLS renegotiation.
  237. proxy_port, proxy_server = await create_tls_proxy(ip_address, port)
  238. camera_url = f"rtsp://bblp:{access_code}@127.0.0.1:{proxy_port}/streaming/live/1"
  239. # ffmpeg command to output MJPEG stream to stdout
  240. cmd = [
  241. ffmpeg,
  242. "-rtsp_transport",
  243. "tcp",
  244. "-rtsp_flags",
  245. "prefer_tcp",
  246. "-timeout",
  247. "30000000", # 30 seconds in microseconds
  248. "-buffer_size",
  249. "1024000", # 1MB buffer
  250. "-max_delay",
  251. "500000", # 0.5 seconds max delay
  252. "-probesize",
  253. "32", # Minimal probing for faster startup
  254. "-analyzeduration",
  255. "0", # Skip format analysis for faster startup
  256. "-fflags",
  257. "nobuffer", # Reduce internal buffering
  258. "-flags",
  259. "low_delay", # Minimize decode latency
  260. "-i",
  261. camera_url,
  262. "-f",
  263. "mjpeg",
  264. "-q:v",
  265. "5",
  266. "-r",
  267. str(fps),
  268. "-an", # No audio
  269. "-", # Output to stdout
  270. ]
  271. # Register disconnect event so stop endpoint can signal us
  272. if stream_id and disconnect_event:
  273. _disconnect_events[stream_id] = disconnect_event
  274. logger.info(
  275. "Starting RTSP camera stream for %s (stream_id=%s, model=%s, fps=%s)", ip_address, stream_id, model, fps
  276. )
  277. logger.debug("ffmpeg command: %s ... (url hidden)", ffmpeg)
  278. # On Windows, spawn ffmpeg in its own process group so that
  279. # terminate() doesn't broadcast CTRL_C_EVENT to uvicorn (#605).
  280. spawn_kwargs: dict = {}
  281. if sys.platform == "win32":
  282. spawn_kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP
  283. jpeg_start = b"\xff\xd8"
  284. jpeg_end = b"\xff\xd9"
  285. reconnect_count = 0
  286. process = None
  287. got_any_frames = False
  288. try:
  289. while reconnect_count <= _RTSP_MAX_RECONNECTS:
  290. # Check for client disconnect before (re)connecting
  291. if disconnect_event and disconnect_event.is_set():
  292. break
  293. if reconnect_count > 0:
  294. logger.info(
  295. "RTSP reconnecting (%d/%d) for %s (stream_id=%s)",
  296. reconnect_count,
  297. _RTSP_MAX_RECONNECTS,
  298. ip_address,
  299. stream_id,
  300. )
  301. await asyncio.sleep(_RTSP_RECONNECT_DELAY)
  302. if disconnect_event and disconnect_event.is_set():
  303. break
  304. # Spawn ffmpeg
  305. process = await asyncio.create_subprocess_exec(
  306. *cmd,
  307. stdout=asyncio.subprocess.PIPE,
  308. stderr=asyncio.subprocess.PIPE,
  309. **spawn_kwargs,
  310. )
  311. if stream_id:
  312. _active_streams[stream_id] = process
  313. import time as _time
  314. _spawned_ffmpeg_pids[process.pid] = _time.time()
  315. # Brief check for immediate startup failures
  316. await asyncio.sleep(0.1)
  317. if process.returncode is not None:
  318. stderr = await process.stderr.read()
  319. stderr_text = _summarize_ffmpeg_stderr(stderr.decode(errors="replace"))
  320. logger.error("ffmpeg failed immediately (attempt %d): %s", reconnect_count + 1, stderr_text)
  321. _spawned_ffmpeg_pids.pop(process.pid, None)
  322. if not got_any_frames and reconnect_count == 0:
  323. # First attempt failed immediately — camera is likely unreachable
  324. yield (
  325. b"--frame\r\n"
  326. b"Content-Type: text/plain\r\n\r\n"
  327. b"Error: Camera connection failed. Check printer is on and camera is enabled.\r\n"
  328. )
  329. return
  330. reconnect_count += 1
  331. continue
  332. # Read JPEG frames from ffmpeg stdout
  333. buffer = b""
  334. stream_ended = False
  335. client_gone = False
  336. while True:
  337. if disconnect_event and disconnect_event.is_set():
  338. client_gone = True
  339. break
  340. try:
  341. chunk = await asyncio.wait_for(process.stdout.read(8192), timeout=30.0)
  342. if not chunk:
  343. # ffmpeg exited — log stderr and break to reconnect
  344. stderr_text = await _read_ffmpeg_stderr(process)
  345. if stderr_text:
  346. logger.warning("ffmpeg stderr (stream_id=%s): %s", stream_id, stderr_text)
  347. logger.warning("RTSP stream ended for %s (stream_id=%s), will reconnect", ip_address, stream_id)
  348. stream_ended = True
  349. break
  350. buffer += chunk
  351. # Extract complete JPEG frames from buffer
  352. while True:
  353. start_idx = buffer.find(jpeg_start)
  354. if start_idx == -1:
  355. buffer = buffer[-2:] if len(buffer) > 2 else buffer
  356. break
  357. if start_idx > 0:
  358. buffer = buffer[start_idx:]
  359. end_idx = buffer.find(jpeg_end, 2)
  360. if end_idx == -1:
  361. break
  362. frame = buffer[: end_idx + 2]
  363. buffer = buffer[end_idx + 2 :]
  364. got_any_frames = True
  365. if printer_id is not None:
  366. import time
  367. _last_frames[printer_id] = frame
  368. _last_frame_times[printer_id] = time.time()
  369. if stream_id:
  370. _stream_last_frame_times[stream_id] = time.time()
  371. yield (
  372. b"--frame\r\n"
  373. b"Content-Type: image/jpeg\r\n"
  374. b"Content-Length: " + str(len(frame)).encode() + b"\r\n"
  375. b"\r\n" + frame + b"\r\n"
  376. )
  377. except TimeoutError:
  378. stderr_text = await _read_ffmpeg_stderr(process)
  379. if stderr_text:
  380. logger.warning("ffmpeg stderr on timeout: %s", stderr_text)
  381. logger.warning("RTSP read timeout for %s (stream_id=%s)", ip_address, stream_id)
  382. stream_ended = True
  383. break
  384. except asyncio.CancelledError:
  385. logger.info("Camera stream cancelled (stream_id=%s)", stream_id)
  386. client_gone = True
  387. break
  388. except GeneratorExit:
  389. logger.info("Camera stream generator exit (stream_id=%s)", stream_id)
  390. client_gone = True
  391. break
  392. # Clean up this ffmpeg process before reconnecting or exiting
  393. await _terminate_ffmpeg(process, stream_id)
  394. process = None
  395. if client_gone:
  396. break
  397. # Check if stream was explicitly stopped (e.g., by stop endpoint)
  398. if stream_id and stream_id not in _active_streams:
  399. logger.info("Stream %s removed from active streams, stopping reconnect", stream_id)
  400. break
  401. if stream_ended:
  402. reconnect_count += 1
  403. continue
  404. # Normal exit (shouldn't reach here, but be safe)
  405. break
  406. if reconnect_count > _RTSP_MAX_RECONNECTS:
  407. logger.error(
  408. "RTSP max reconnects (%d) reached for %s (stream_id=%s)",
  409. _RTSP_MAX_RECONNECTS,
  410. ip_address,
  411. stream_id,
  412. )
  413. except FileNotFoundError:
  414. logger.error("ffmpeg not found - camera streaming requires ffmpeg")
  415. yield (b"--frame\r\nContent-Type: text/plain\r\n\r\nError: ffmpeg not installed\r\n")
  416. except asyncio.CancelledError:
  417. logger.info("Camera stream task cancelled (stream_id=%s)", stream_id)
  418. except GeneratorExit:
  419. logger.info("Camera stream generator closed (stream_id=%s)", stream_id)
  420. except Exception as e:
  421. logger.exception("Camera stream error: %s", e)
  422. finally:
  423. # Remove from active streams and disconnect events
  424. if stream_id:
  425. _active_streams.pop(stream_id, None)
  426. _disconnect_events.pop(stream_id, None)
  427. _stream_last_frame_times.pop(stream_id, None)
  428. # Clean up frame buffer and timestamps
  429. if printer_id is not None:
  430. _last_frames.pop(printer_id, None)
  431. _last_frame_times.pop(printer_id, None)
  432. _stream_start_times.pop(printer_id, None)
  433. if process:
  434. await _terminate_ffmpeg(process, stream_id)
  435. logger.info("Camera stream stopped for %s (stream_id=%s)", ip_address, stream_id)
  436. # Shut down the TLS proxy
  437. proxy_server.close()
  438. await proxy_server.wait_closed()
  439. @router.post("/camera/stream-token")
  440. async def create_stream_token(
  441. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  442. ):
  443. """Create a reusable token for camera stream/snapshot access.
  444. Returns a token valid for 60 minutes that can be appended as ?token=xxx
  445. to camera stream/snapshot URLs loaded via <img> tags.
  446. """
  447. return {"token": await create_camera_stream_token()}
  448. @router.get("/{printer_id}/camera/stream")
  449. async def camera_stream(
  450. printer_id: int,
  451. request: Request,
  452. fps: int = 10,
  453. db: AsyncSession = Depends(get_db),
  454. _: None = RequireCameraStreamTokenIfAuthEnabled,
  455. ):
  456. """Stream live video from printer camera as MJPEG.
  457. This endpoint returns a multipart MJPEG stream that can be used directly
  458. in an <img> tag or video player.
  459. Requires a stream token query param (?token=xxx) when auth is enabled.
  460. Uses external camera if configured, otherwise uses built-in camera:
  461. - External: MJPEG, RTSP, or HTTP snapshot
  462. - A1/P1: Chamber image protocol (port 6000)
  463. - X1/H2/P2: RTSP via ffmpeg (port 322)
  464. Args:
  465. printer_id: Printer ID
  466. fps: Target frames per second (default: 10, max: 30)
  467. """
  468. printer = await get_printer_or_404(printer_id, db)
  469. # Check for external camera first
  470. if printer.external_camera_enabled and printer.external_camera_url:
  471. import time
  472. from backend.app.services.external_camera import generate_mjpeg_stream
  473. # Limit external camera FPS to reduce browser load
  474. fps = min(max(fps, 1), 15)
  475. logger.info(
  476. "Using external camera (%s) for printer %s at %s fps", printer.external_camera_type, printer_id, fps
  477. )
  478. # Track stream start
  479. _stream_start_times[printer_id] = time.time()
  480. _active_external_streams.add(printer_id)
  481. async def external_stream_wrapper():
  482. """Wrap external stream to track start/stop and update frame times."""
  483. try:
  484. async for frame in generate_mjpeg_stream(
  485. printer.external_camera_url, printer.external_camera_type, fps
  486. ):
  487. # generate_mjpeg_stream already handles rate limiting;
  488. # just track frame times for stall detection
  489. _last_frame_times[printer_id] = time.time()
  490. yield frame
  491. finally:
  492. _active_external_streams.discard(printer_id)
  493. logger.info("External camera stream ended for printer %s", printer_id)
  494. return StreamingResponse(
  495. external_stream_wrapper(),
  496. media_type="multipart/x-mixed-replace; boundary=frame",
  497. headers={
  498. "Cache-Control": "no-cache, no-store, must-revalidate",
  499. "Pragma": "no-cache",
  500. "Expires": "0",
  501. },
  502. )
  503. # Validate FPS - A1/P1 models max out at ~5 FPS
  504. if is_chamber_image_model(printer.model):
  505. fps = min(max(fps, 1), 5)
  506. else:
  507. fps = min(max(fps, 1), 30)
  508. # Choose the appropriate stream generator based on model
  509. if is_chamber_image_model(printer.model):
  510. stream_generator = generate_chamber_mjpeg_stream
  511. logger.info("Using chamber image protocol for %s", printer.model)
  512. else:
  513. stream_generator = generate_rtsp_mjpeg_stream
  514. logger.info("Using RTSP protocol for %s", printer.model)
  515. # Track stream start time. Set only if absent so the value reflects when
  516. # the SHARED upstream first started streaming, not when each new viewer
  517. # attached — otherwise /camera/status would report stream_uptime jumping
  518. # backward whenever a second viewer joins. The upstream generator's
  519. # finally clears this entry when the upstream actually ends.
  520. import time
  521. _stream_start_times.setdefault(printer_id, time.time())
  522. # Fan-out broadcaster (#1089): one upstream connection per printer, shared
  523. # across all viewers. Most Bambu printers only allow a single concurrent
  524. # camera connection, so opening the same printer in two tabs would
  525. # otherwise kick the first viewer off. The broadcaster owns the single
  526. # upstream and the per-viewer disconnect handling.
  527. #
  528. # Note: the upstream's fps is fixed by the first viewer who creates the
  529. # broadcaster. Concurrent viewers share that rate; new viewers after
  530. # teardown create a fresh broadcaster at their requested fps.
  531. fanout_key = f"printer-{printer_id}"
  532. upstream_stream_id = f"{printer_id}-fanout"
  533. def _factory(disconnect_event: asyncio.Event):
  534. # Re-bind locals into the closure so the async generator below sees
  535. # them — disconnect_event is owned by the broadcaster and signalled
  536. # when the last subscriber leaves (after the grace window).
  537. return stream_generator(
  538. ip_address=printer.ip_address,
  539. access_code=printer.access_code,
  540. model=printer.model,
  541. fps=fps,
  542. stream_id=upstream_stream_id,
  543. disconnect_event=disconnect_event,
  544. printer_id=printer_id,
  545. )
  546. # Subscribe with a one-shot retry to close a tiny race: the grace-window
  547. # teardown can flip the broadcaster to `stopped=True` between the registry
  548. # lookup and our subscribe call. The retry forces the registry to mint a
  549. # fresh broadcaster (since the now-stopped one is replaced), and the second
  550. # subscribe is guaranteed to land on it before any teardown can fire.
  551. broadcaster: MjpegBroadcaster = await get_or_create_broadcaster(fanout_key, _factory)
  552. try:
  553. queue = await broadcaster.subscribe()
  554. except RuntimeError:
  555. broadcaster = await get_or_create_broadcaster(fanout_key, _factory)
  556. queue = await broadcaster.subscribe()
  557. logger.info(
  558. "Camera viewer attached to %s (subscribers=%d)",
  559. fanout_key,
  560. broadcaster.subscriber_count,
  561. )
  562. async def _is_disconnected() -> bool:
  563. try:
  564. return await request.is_disconnected()
  565. except Exception:
  566. # Older starlette/uvicorn can raise during teardown — treat that
  567. # as "client gone" so the subscriber cleanly unsubscribes.
  568. return True
  569. def _log_detach(remaining: int) -> None:
  570. logger.info("Camera viewer detached from %s (subscribers=%d)", fanout_key, remaining)
  571. async def _generate():
  572. async for chunk in iter_subscriber(
  573. broadcaster,
  574. queue,
  575. is_disconnected=_is_disconnected,
  576. on_unsubscribe=_log_detach,
  577. ):
  578. yield chunk
  579. return StreamingResponse(
  580. _generate(),
  581. media_type="multipart/x-mixed-replace; boundary=frame",
  582. headers={
  583. "Cache-Control": "no-cache, no-store, must-revalidate",
  584. "Pragma": "no-cache",
  585. "Expires": "0",
  586. },
  587. )
  588. @router.api_route("/{printer_id}/camera/stop", methods=["GET", "POST"])
  589. async def stop_camera_stream(
  590. printer_id: int,
  591. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  592. ):
  593. """Stop all active camera streams for a printer.
  594. This can be called by the frontend when the camera window is closed.
  595. Accepts both GET and POST (POST for sendBeacon compatibility).
  596. """
  597. stopped = 0
  598. # Tear down the fan-out broadcaster first (#1089). This cleanly notifies
  599. # all subscribed viewers and asks the upstream generator to stop
  600. # reconnecting before we fall back to forcefully killing the process below.
  601. if await shutdown_broadcaster(f"printer-{printer_id}"):
  602. logger.info("Shut down camera fan-out broadcaster for printer %s", printer_id)
  603. # Stop ffmpeg/RTSP streams
  604. to_remove = []
  605. for stream_id, process in list(_active_streams.items()):
  606. if stream_id.startswith(f"{printer_id}-"):
  607. to_remove.append(stream_id)
  608. # Signal the generator to stop reconnecting BEFORE killing the process
  609. event = _disconnect_events.get(stream_id)
  610. if event:
  611. event.set()
  612. if process.returncode is None:
  613. try:
  614. process.terminate()
  615. try:
  616. await asyncio.wait_for(process.wait(), timeout=2.0)
  617. except TimeoutError:
  618. logger.warning("ffmpeg didn't terminate gracefully, killing (stream_id=%s)", stream_id)
  619. process.kill()
  620. await process.wait()
  621. stopped += 1
  622. logger.info("Terminated ffmpeg process for stream %s", stream_id)
  623. except ProcessLookupError:
  624. pass # Process already dead
  625. except OSError as e:
  626. logger.warning("Error stopping stream %s: %s", stream_id, e)
  627. _spawned_ffmpeg_pids.pop(process.pid, None)
  628. for stream_id in to_remove:
  629. _active_streams.pop(stream_id, None)
  630. _disconnect_events.pop(stream_id, None)
  631. _stream_last_frame_times.pop(stream_id, None)
  632. # Stop chamber image streams
  633. to_remove_chamber = []
  634. for stream_id, (_reader, writer) in list(_active_chamber_streams.items()):
  635. if stream_id.startswith(f"{printer_id}-"):
  636. to_remove_chamber.append(stream_id)
  637. # Signal the generator to stop
  638. event = _disconnect_events.get(stream_id)
  639. if event:
  640. event.set()
  641. try:
  642. writer.close()
  643. stopped += 1
  644. logger.info("Closed chamber image connection for stream %s", stream_id)
  645. except OSError as e:
  646. logger.warning("Error stopping chamber stream %s: %s", stream_id, e)
  647. for stream_id in to_remove_chamber:
  648. _active_chamber_streams.pop(stream_id, None)
  649. _disconnect_events.pop(stream_id, None)
  650. _stream_last_frame_times.pop(stream_id, None)
  651. logger.info("Stopped %s camera stream(s) for printer %s", stopped, printer_id)
  652. return {"stopped": stopped}
  653. @router.get("/{printer_id}/camera/snapshot")
  654. async def camera_snapshot(
  655. printer_id: int,
  656. db: AsyncSession = Depends(get_db),
  657. _: None = RequireCameraStreamTokenIfAuthEnabled,
  658. ):
  659. """Capture a single frame from the printer camera.
  660. Returns a JPEG image.
  661. Requires a stream token query param (?token=xxx) when auth is enabled.
  662. """
  663. import tempfile
  664. from pathlib import Path
  665. printer = await get_printer_or_404(printer_id, db)
  666. # Check for external camera first
  667. if printer.external_camera_enabled and printer.external_camera_url:
  668. from backend.app.services.external_camera import capture_frame
  669. frame_data = await capture_frame(printer.external_camera_url, printer.external_camera_type, timeout=15)
  670. if not frame_data:
  671. raise HTTPException(
  672. status_code=503,
  673. detail="Failed to capture frame from external camera.",
  674. )
  675. return Response(
  676. content=frame_data,
  677. media_type="image/jpeg",
  678. headers={
  679. "Cache-Control": "no-cache, no-store, must-revalidate",
  680. "Content-Disposition": f'inline; filename="snapshot_{printer_id}.jpg"',
  681. },
  682. )
  683. # Create temporary file for the snapshot (0600 so only the app user can read it)
  684. fd, tmp_name = tempfile.mkstemp(suffix=".jpg")
  685. os.close(fd)
  686. temp_path = Path(tmp_name)
  687. temp_path.chmod(0o600)
  688. try:
  689. success = await capture_camera_frame(
  690. ip_address=printer.ip_address,
  691. access_code=printer.access_code,
  692. model=printer.model,
  693. output_path=temp_path,
  694. timeout=15,
  695. )
  696. if not success:
  697. raise HTTPException(
  698. status_code=503,
  699. detail="Failed to capture camera frame. Ensure printer is on and camera is enabled.",
  700. )
  701. # Read and return the image
  702. with open(temp_path, "rb") as f:
  703. image_data = f.read()
  704. return Response(
  705. content=image_data,
  706. media_type="image/jpeg",
  707. headers={
  708. "Cache-Control": "no-cache, no-store, must-revalidate",
  709. "Content-Disposition": f'inline; filename="snapshot_{printer_id}.jpg"',
  710. },
  711. )
  712. finally:
  713. # Clean up temp file
  714. if temp_path.exists():
  715. temp_path.unlink()
  716. @router.get("/{printer_id}/camera/test")
  717. async def test_camera(
  718. printer_id: int,
  719. db: AsyncSession = Depends(get_db),
  720. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  721. ):
  722. """Test camera connection for a printer.
  723. Returns success status and any error message.
  724. """
  725. printer = await get_printer_or_404(printer_id, db)
  726. result = await test_camera_connection(
  727. ip_address=printer.ip_address,
  728. access_code=printer.access_code,
  729. model=printer.model,
  730. )
  731. return result
  732. @router.get("/{printer_id}/camera/status")
  733. async def camera_status(
  734. printer_id: int,
  735. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  736. ):
  737. """Get the status of an active camera stream.
  738. Returns whether a stream is active and when the last frame was received.
  739. Used by the frontend to detect stalled streams and auto-reconnect.
  740. """
  741. import time
  742. # Check if there's an active stream for this printer
  743. has_active_stream = False
  744. # Check external camera streams
  745. if printer_id in _active_external_streams:
  746. has_active_stream = True
  747. # Check ffmpeg/RTSP streams
  748. if not has_active_stream:
  749. for stream_id in _active_streams:
  750. if stream_id.startswith(f"{printer_id}-"):
  751. process = _active_streams[stream_id]
  752. if process.returncode is None:
  753. has_active_stream = True
  754. break
  755. # Check chamber image streams
  756. if not has_active_stream:
  757. for stream_id in _active_chamber_streams:
  758. if stream_id.startswith(f"{printer_id}-"):
  759. has_active_stream = True
  760. break
  761. # Get timing information
  762. current_time = time.time()
  763. last_frame_time = _last_frame_times.get(printer_id)
  764. stream_start_time = _stream_start_times.get(printer_id)
  765. # Calculate seconds since last frame
  766. seconds_since_frame = None
  767. if last_frame_time is not None:
  768. seconds_since_frame = current_time - last_frame_time
  769. # Calculate stream uptime
  770. stream_uptime = None
  771. if stream_start_time is not None:
  772. stream_uptime = current_time - stream_start_time
  773. return {
  774. "active": has_active_stream,
  775. "has_frames": printer_id in _last_frames,
  776. "seconds_since_frame": seconds_since_frame,
  777. "stream_uptime": stream_uptime,
  778. # Consider stalled if no frame for more than 10 seconds after stream started
  779. "stalled": (
  780. has_active_stream
  781. and stream_uptime is not None
  782. and stream_uptime > 5 # Give 5 seconds for stream to start
  783. and (seconds_since_frame is None or seconds_since_frame > 10)
  784. ),
  785. }
  786. @router.post("/{printer_id}/camera/external/test")
  787. async def test_external_camera(
  788. printer_id: int,
  789. url: str,
  790. camera_type: str,
  791. db: AsyncSession = Depends(get_db),
  792. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  793. ):
  794. """Test external camera connection.
  795. Args:
  796. printer_id: Printer ID (for authorization)
  797. url: Camera URL or USB device path to test
  798. camera_type: Camera type ("mjpeg", "rtsp", "snapshot", "usb")
  799. Returns:
  800. Dict with {success: bool, error?: str, resolution?: str}
  801. """
  802. # Verify printer exists (for authorization)
  803. await get_printer_or_404(printer_id, db)
  804. from backend.app.services.external_camera import test_connection
  805. return await test_connection(url, camera_type)
  806. @router.get("/{printer_id}/camera/check-plate")
  807. async def check_plate_empty(
  808. printer_id: int,
  809. plate_type: str | None = None,
  810. use_external: bool = False,
  811. include_debug_image: bool = False,
  812. db: AsyncSession = Depends(get_db),
  813. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  814. ):
  815. """Check if the build plate is empty using camera vision.
  816. Uses calibration-based difference detection - compares current frame
  817. to a reference image of the empty plate.
  818. IMPORTANT: Chamber light must be ON for reliable detection.
  819. Args:
  820. printer_id: Printer ID
  821. plate_type: Type of build plate (e.g., "High Temp Plate") for calibration lookup
  822. use_external: If True, prefer external camera over built-in
  823. include_debug_image: If True, return URL to annotated debug image
  824. Returns:
  825. Dict with detection results:
  826. - is_empty: bool - Whether plate appears empty
  827. - confidence: float - Confidence level (0.0 to 1.0)
  828. - difference_percent: float - How different from calibration reference
  829. - message: str - Human-readable result message
  830. - needs_calibration: bool - True if calibration is required
  831. - light_warning: bool - True if chamber light is off
  832. """
  833. from backend.app.services.plate_detection import (
  834. check_plate_empty as do_check,
  835. is_plate_detection_available,
  836. )
  837. from backend.app.services.printer_manager import printer_manager
  838. # Check printer exists first (before OpenCV check)
  839. printer = await get_printer_or_404(printer_id, db)
  840. if not is_plate_detection_available():
  841. raise HTTPException(
  842. status_code=503,
  843. detail="Plate detection not available. Install opencv-python-headless to enable.",
  844. )
  845. # Check chamber light status
  846. light_warning = False
  847. state = printer_manager.get_status(printer_id)
  848. if state and not state.chamber_light:
  849. light_warning = True
  850. from backend.app.services.plate_detection import PlateDetector
  851. # Build ROI tuple from printer settings if available
  852. roi = None
  853. if all(
  854. [
  855. printer.plate_detection_roi_x is not None,
  856. printer.plate_detection_roi_y is not None,
  857. printer.plate_detection_roi_w is not None,
  858. printer.plate_detection_roi_h is not None,
  859. ]
  860. ):
  861. roi = (
  862. printer.plate_detection_roi_x,
  863. printer.plate_detection_roi_y,
  864. printer.plate_detection_roi_w,
  865. printer.plate_detection_roi_h,
  866. )
  867. result = await do_check(
  868. printer_id=printer.id,
  869. ip_address=printer.ip_address,
  870. access_code=printer.access_code,
  871. model=printer.model,
  872. plate_type=plate_type,
  873. include_debug_image=include_debug_image,
  874. external_camera_url=printer.external_camera_url if printer.external_camera_enabled else None,
  875. external_camera_type=printer.external_camera_type if printer.external_camera_enabled else None,
  876. use_external=use_external,
  877. roi=roi,
  878. )
  879. # Get reference count for the response
  880. detector = PlateDetector()
  881. ref_count = detector.get_calibration_count(printer.id)
  882. response = result.to_dict()
  883. response["light_warning"] = light_warning
  884. response["reference_count"] = ref_count
  885. response["max_references"] = detector.MAX_REFERENCES
  886. # Include current ROI in response
  887. if roi:
  888. response["roi"] = {"x": roi[0], "y": roi[1], "w": roi[2], "h": roi[3]}
  889. else:
  890. # Return default ROI
  891. response["roi"] = {"x": 0.15, "y": 0.35, "w": 0.70, "h": 0.55}
  892. # If debug image requested and available, encode as base64 data URL
  893. if include_debug_image and result.debug_image:
  894. import base64
  895. b64_image = base64.b64encode(result.debug_image).decode("utf-8")
  896. response["debug_image_url"] = f"data:image/jpeg;base64,{b64_image}"
  897. return response
  898. @router.post("/{printer_id}/camera/plate-detection/calibrate")
  899. async def calibrate_plate_detection(
  900. printer_id: int,
  901. label: str | None = None,
  902. use_external: bool = False,
  903. db: AsyncSession = Depends(get_db),
  904. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  905. ):
  906. """Calibrate plate detection by capturing a reference image of the empty plate.
  907. The plate MUST be empty when calling this endpoint. The captured image
  908. will be used as the reference for future detection comparisons.
  909. Supports up to 5 reference images per printer. When adding a 6th, the oldest
  910. is automatically removed.
  911. IMPORTANT: Chamber light should be ON for calibration.
  912. Args:
  913. printer_id: Printer ID
  914. label: Optional label for this reference (e.g., "High Temp Plate", "Wham Bam")
  915. use_external: If True, prefer external camera over built-in
  916. Returns:
  917. Dict with:
  918. - success: bool - Whether calibration succeeded
  919. - message: str - Status message
  920. - index: int - The reference slot used (0-4)
  921. """
  922. from backend.app.services.plate_detection import (
  923. calibrate_plate,
  924. is_plate_detection_available,
  925. )
  926. from backend.app.services.printer_manager import printer_manager
  927. # Check printer exists first (before OpenCV check)
  928. printer = await get_printer_or_404(printer_id, db)
  929. if not is_plate_detection_available():
  930. raise HTTPException(
  931. status_code=503,
  932. detail="Plate detection not available. Install opencv-python-headless to enable.",
  933. )
  934. # Check chamber light - warn but don't block
  935. state = printer_manager.get_status(printer_id)
  936. light_warning = state and not state.chamber_light
  937. success, message, index = await calibrate_plate(
  938. printer_id=printer.id,
  939. ip_address=printer.ip_address,
  940. access_code=printer.access_code,
  941. model=printer.model,
  942. label=label,
  943. external_camera_url=printer.external_camera_url if printer.external_camera_enabled else None,
  944. external_camera_type=printer.external_camera_type if printer.external_camera_enabled else None,
  945. use_external=use_external,
  946. )
  947. if light_warning and success:
  948. message += " (Warning: Chamber light was off)"
  949. return {"success": success, "message": message, "index": index}
  950. @router.delete("/{printer_id}/camera/plate-detection/calibrate")
  951. async def delete_plate_calibration(
  952. printer_id: int,
  953. plate_type: str | None = None,
  954. db: AsyncSession = Depends(get_db),
  955. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  956. ):
  957. """Delete the plate detection calibration for a printer and plate type.
  958. Args:
  959. printer_id: Printer ID
  960. plate_type: Type of build plate (if None, deletes legacy non-plate-specific calibration)
  961. Returns:
  962. Dict with:
  963. - success: bool - Whether deletion succeeded
  964. - message: str - Status message
  965. """
  966. from backend.app.services.plate_detection import (
  967. delete_calibration,
  968. is_plate_detection_available,
  969. )
  970. # Verify printer exists first (before OpenCV check)
  971. await get_printer_or_404(printer_id, db)
  972. if not is_plate_detection_available():
  973. raise HTTPException(
  974. status_code=503,
  975. detail="Plate detection not available. Install opencv-python-headless to enable.",
  976. )
  977. deleted = delete_calibration(printer_id, plate_type)
  978. plate_msg = f" for '{plate_type}'" if plate_type else ""
  979. return {
  980. "success": deleted,
  981. "message": f"Calibration deleted{plate_msg}" if deleted else f"No calibration found{plate_msg}",
  982. }
  983. @router.get("/{printer_id}/camera/plate-detection/status")
  984. async def get_plate_detection_status(
  985. printer_id: int,
  986. plate_type: str | None = None,
  987. db: AsyncSession = Depends(get_db),
  988. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  989. ):
  990. """Check plate detection status for a printer and plate type.
  991. Returns:
  992. Dict with:
  993. - available: bool - Whether OpenCV is installed
  994. - calibrated: bool - Whether printer has calibration for this plate type
  995. - plate_type: str - The plate type queried
  996. - chamber_light: bool - Whether chamber light is on
  997. - message: str - Status message
  998. """
  999. from backend.app.services.plate_detection import (
  1000. get_calibration_status,
  1001. is_plate_detection_available,
  1002. )
  1003. from backend.app.services.printer_manager import printer_manager
  1004. # Verify printer exists first (before OpenCV check)
  1005. await get_printer_or_404(printer_id, db)
  1006. if not is_plate_detection_available():
  1007. return {
  1008. "available": False,
  1009. "calibrated": False,
  1010. "plate_type": plate_type,
  1011. "chamber_light": False,
  1012. "message": "OpenCV not installed",
  1013. }
  1014. # Get chamber light status
  1015. state = printer_manager.get_status(printer_id)
  1016. chamber_light = state.chamber_light if state else False
  1017. status = get_calibration_status(printer_id, plate_type)
  1018. status["chamber_light"] = chamber_light
  1019. return status
  1020. @router.get("/{printer_id}/camera/plate-detection/references")
  1021. async def get_plate_references(
  1022. printer_id: int,
  1023. db: AsyncSession = Depends(get_db),
  1024. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  1025. ):
  1026. """Get all calibration references for a printer with metadata.
  1027. Returns list of references with index, label, timestamp, and thumbnail URL.
  1028. """
  1029. from backend.app.services.plate_detection import PlateDetector, is_plate_detection_available
  1030. # Verify printer exists first (before OpenCV check)
  1031. await get_printer_or_404(printer_id, db)
  1032. if not is_plate_detection_available():
  1033. raise HTTPException(503, "Plate detection not available")
  1034. detector = PlateDetector()
  1035. references = detector.get_references(printer_id)
  1036. # Add thumbnail URLs
  1037. for ref in references:
  1038. ref["thumbnail_url"] = (
  1039. f"/api/v1/printers/{printer_id}/camera/plate-detection/references/{ref['index']}/thumbnail"
  1040. )
  1041. return {
  1042. "references": references,
  1043. "max_references": detector.MAX_REFERENCES,
  1044. }
  1045. @router.get("/{printer_id}/camera/plate-detection/references/{index}/thumbnail")
  1046. async def get_reference_thumbnail(
  1047. printer_id: int,
  1048. index: int,
  1049. db: AsyncSession = Depends(get_db),
  1050. _: None = RequireCameraStreamTokenIfAuthEnabled,
  1051. ):
  1052. """Get thumbnail image for a calibration reference.
  1053. Requires a stream token query param (?token=xxx) when auth is enabled.
  1054. """
  1055. from fastapi.responses import Response
  1056. from backend.app.services.plate_detection import PlateDetector, is_plate_detection_available
  1057. # Verify printer exists first (before OpenCV check)
  1058. await get_printer_or_404(printer_id, db)
  1059. if not is_plate_detection_available():
  1060. raise HTTPException(503, "Plate detection not available")
  1061. detector = PlateDetector()
  1062. thumbnail = detector.get_reference_thumbnail(printer_id, index)
  1063. if thumbnail is None:
  1064. raise HTTPException(404, "Reference not found")
  1065. return Response(content=thumbnail, media_type="image/jpeg")
  1066. @router.put("/{printer_id}/camera/plate-detection/references/{index}")
  1067. async def update_reference_label(
  1068. printer_id: int,
  1069. index: int,
  1070. label: str,
  1071. db: AsyncSession = Depends(get_db),
  1072. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  1073. ):
  1074. """Update the label for a calibration reference."""
  1075. from backend.app.services.plate_detection import PlateDetector, is_plate_detection_available
  1076. # Verify printer exists first (before OpenCV check)
  1077. await get_printer_or_404(printer_id, db)
  1078. if not is_plate_detection_available():
  1079. raise HTTPException(503, "Plate detection not available")
  1080. detector = PlateDetector()
  1081. success = detector.update_reference_label(printer_id, index, label)
  1082. if not success:
  1083. raise HTTPException(404, "Reference not found")
  1084. return {"success": True, "index": index, "label": label}
  1085. @router.delete("/{printer_id}/camera/plate-detection/references/{index}")
  1086. async def delete_reference(
  1087. printer_id: int,
  1088. index: int,
  1089. db: AsyncSession = Depends(get_db),
  1090. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  1091. ):
  1092. """Delete a specific calibration reference."""
  1093. from backend.app.services.plate_detection import PlateDetector, is_plate_detection_available
  1094. # Verify printer exists first (before OpenCV check)
  1095. await get_printer_or_404(printer_id, db)
  1096. if not is_plate_detection_available():
  1097. raise HTTPException(503, "Plate detection not available")
  1098. detector = PlateDetector()
  1099. success = detector.delete_reference(printer_id, index)
  1100. if not success:
  1101. raise HTTPException(404, "Reference not found")
  1102. return {"success": True, "message": "Reference deleted"}
  1103. def _scan_bambu_ffmpeg_pids() -> list[int]:
  1104. """Scan /proc for ffmpeg processes with Bambu RTSP URLs.
  1105. These are definitely ours — no other software connects to rtsp(s)://bblp:.
  1106. This catches orphans that survive app restarts and are not in any tracking dict.
  1107. """
  1108. import os
  1109. pids = []
  1110. try:
  1111. for entry in os.listdir("/proc"):
  1112. if not entry.isdigit():
  1113. continue
  1114. try:
  1115. with open(f"/proc/{entry}/cmdline", "rb") as f:
  1116. cmdline = f.read()
  1117. # Match both rtsp:// (via TLS proxy) and rtsps:// (direct)
  1118. if b"ffmpeg" in cmdline and (b"rtsp://bblp:" in cmdline or b"rtsps://bblp:" in cmdline):
  1119. pids.append(int(entry))
  1120. except (OSError, PermissionError, ValueError):
  1121. continue
  1122. except OSError:
  1123. pass
  1124. return pids
  1125. async def cleanup_orphaned_streams():
  1126. """Clean up orphaned ffmpeg processes and stale stream entries.
  1127. Called periodically from the background task loop in main.py.
  1128. Three-layer cleanup:
  1129. 1. /proc scan — finds ALL Bambu ffmpeg processes on the system, even those
  1130. from previous app sessions. This is the nuclear safety net.
  1131. 2. _spawned_ffmpeg_pids — tracks PIDs spawned this session, catches orphans
  1132. that were removed from _active_streams but not killed.
  1133. 3. _active_streams — kills stale entries with no recent frames.
  1134. """
  1135. import os
  1136. import signal
  1137. import time
  1138. cleaned = 0
  1139. now = time.time()
  1140. # Collect PIDs that are legitimately in-use (active stream, process alive)
  1141. active_pids = {proc.pid for proc in _active_streams.values() if proc.returncode is None}
  1142. # Also exclude PIDs from one-shot snapshot captures (Obico detection, finish photos, etc.)
  1143. from backend.app.services.camera import _active_capture_pids
  1144. active_pids |= _active_capture_pids
  1145. # 1. /proc scan — catch ALL orphaned Bambu ffmpeg processes on the system.
  1146. # Any ffmpeg with rtsp(s)://bblp: that is NOT in an active stream is orphaned.
  1147. for pid in _scan_bambu_ffmpeg_pids():
  1148. if pid in active_pids:
  1149. continue
  1150. logger.info("Killing orphaned ffmpeg process found via /proc (pid=%d)", pid)
  1151. try:
  1152. os.kill(pid, signal.SIGKILL)
  1153. except (ProcessLookupError, OSError):
  1154. pass
  1155. _spawned_ffmpeg_pids.pop(pid, None)
  1156. cleaned += 1
  1157. # 2. Clean up _spawned_ffmpeg_pids entries for dead processes
  1158. for pid in list(_spawned_ffmpeg_pids):
  1159. try:
  1160. os.kill(pid, 0) # existence check
  1161. except (ProcessLookupError, OSError):
  1162. _spawned_ffmpeg_pids.pop(pid, None)
  1163. # 3. Clean up _active_streams entries with dead processes
  1164. dead_streams = [sid for sid, proc in _active_streams.items() if proc.returncode is not None]
  1165. for sid in dead_streams:
  1166. proc = _active_streams.pop(sid, None)
  1167. if proc:
  1168. _spawned_ffmpeg_pids.pop(proc.pid, None)
  1169. cleaned += 1
  1170. # 4. Kill stale active streams (alive but no frames for >30s)
  1171. # Uses per-stream timestamps to avoid false "fresh" readings from newer streams
  1172. for sid, proc in list(_active_streams.items()):
  1173. if proc.returncode is not None:
  1174. continue
  1175. # Per-stream frame time is authoritative; fall back to per-printer
  1176. stream_last_frame = _stream_last_frame_times.get(sid)
  1177. if stream_last_frame is None:
  1178. try:
  1179. printer_id = int(sid.split("-", 1)[0])
  1180. except (ValueError, IndexError):
  1181. continue
  1182. stream_last_frame = _last_frame_times.get(printer_id)
  1183. spawn_time = _spawned_ffmpeg_pids.get(proc.pid, now)
  1184. if stream_last_frame is None:
  1185. stream_last_frame = spawn_time
  1186. if now - spawn_time > 60 and now - stream_last_frame > 30:
  1187. logger.info("Killing stale ffmpeg stream %s (no frames for %.0fs)", sid, now - stream_last_frame)
  1188. # Signal the generator to stop reconnecting
  1189. event = _disconnect_events.get(sid)
  1190. if event:
  1191. event.set()
  1192. try:
  1193. proc.kill()
  1194. await proc.wait()
  1195. except (ProcessLookupError, OSError):
  1196. pass
  1197. _active_streams.pop(sid, None)
  1198. _disconnect_events.pop(sid, None)
  1199. _stream_last_frame_times.pop(sid, None)
  1200. _spawned_ffmpeg_pids.pop(proc.pid, None)
  1201. cleaned += 1
  1202. # 4. Clean stale chamber stream entries
  1203. dead_chamber = [sid for sid, (_reader, writer) in _active_chamber_streams.items() if writer.is_closing()]
  1204. for sid in dead_chamber:
  1205. _active_chamber_streams.pop(sid, None)
  1206. cleaned += 1
  1207. if cleaned:
  1208. logger.info("Cleaned up %d orphaned camera stream(s)", cleaned)