camera.py 62 KB

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