camera.py 47 KB

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