camera.py 50 KB

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