camera.py 54 KB

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