camera.py 51 KB

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