camera.py 47 KB

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