camera.py 50 KB

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