camera.py 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711
  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. import uuid
  567. from backend.app.services.external_camera import generate_mjpeg_stream
  568. # Limit external camera FPS to reduce browser load
  569. fps = min(max(fps, 1), 15)
  570. logger.info(
  571. "Using external camera (%s) for printer %s at %s fps", printer.external_camera_type, printer_id, fps
  572. )
  573. # Register the stream into the SAME registries the RTSP/chamber paths use
  574. # (#2675) so `/camera/stop` and cleanup_orphaned_streams can find and kill
  575. # a leaked ffmpeg holding a USB device open. Before this, external streams
  576. # only tracked _active_external_streams and were structurally invisible to
  577. # both the stop endpoint and the janitor. The stream_id keeps the
  578. # `{printer_id}-` prefix both scanners key on, plus a unique suffix so two
  579. # concurrent viewers of one printer don't clobber each other's entry.
  580. stream_id = f"{printer_id}-ext-{uuid.uuid4().hex[:8]}"
  581. stop_event = asyncio.Event()
  582. _disconnect_events[stream_id] = stop_event
  583. # Track stream start
  584. _stream_start_times[printer_id] = time.time()
  585. _active_external_streams.add(printer_id)
  586. # Mutable holder so the wrapper's finally can unregister whatever process
  587. # is currently registered (the RTSP path may respawn across reconnects).
  588. current_proc: dict[str, asyncio.subprocess.Process] = {}
  589. def _register_external_process(proc: asyncio.subprocess.Process) -> None:
  590. prev = current_proc.get("proc")
  591. if prev is not None and prev.pid != proc.pid:
  592. _spawned_ffmpeg_pids.pop(prev.pid, None)
  593. current_proc["proc"] = proc
  594. _active_streams[stream_id] = proc
  595. _spawned_ffmpeg_pids[proc.pid] = time.time()
  596. _stream_last_frame_times[stream_id] = time.time()
  597. async def external_stream_wrapper():
  598. """Wrap external stream to track start/stop and update frame times."""
  599. try:
  600. async for frame in generate_mjpeg_stream(
  601. printer.external_camera_url,
  602. printer.external_camera_type,
  603. fps,
  604. on_process=_register_external_process,
  605. stop_event=stop_event,
  606. ):
  607. # generate_mjpeg_stream already handles rate limiting;
  608. # track frame times (per-printer + per-stream) for stall detection
  609. now = time.time()
  610. _last_frame_times[printer_id] = now
  611. _stream_last_frame_times[stream_id] = now
  612. yield frame
  613. finally:
  614. # Best-effort unregister. If an abrupt disconnect skips this
  615. # finally, the registry entries persist — which is exactly what
  616. # lets the stop endpoint / janitor reap the leaked process.
  617. stop_event.set()
  618. proc = current_proc.get("proc")
  619. if proc is not None:
  620. _spawned_ffmpeg_pids.pop(proc.pid, None)
  621. _active_streams.pop(stream_id, None)
  622. _disconnect_events.pop(stream_id, None)
  623. _stream_last_frame_times.pop(stream_id, None)
  624. _active_external_streams.discard(printer_id)
  625. logger.info("External camera stream ended for printer %s", printer_id)
  626. return StreamingResponse(
  627. external_stream_wrapper(),
  628. media_type="multipart/x-mixed-replace; boundary=frame",
  629. headers={
  630. "Cache-Control": "no-cache, no-store, must-revalidate",
  631. "Pragma": "no-cache",
  632. "Expires": "0",
  633. },
  634. )
  635. # Validate FPS - A1/P1 models max out at ~5 FPS
  636. if is_chamber_image_model(printer.model):
  637. fps = min(max(fps, 1), 5)
  638. else:
  639. fps = min(max(fps, 1), 30)
  640. # Choose the appropriate stream generator based on model
  641. if is_chamber_image_model(printer.model):
  642. stream_generator = generate_chamber_mjpeg_stream
  643. logger.info("Using chamber image protocol for %s", printer.model)
  644. else:
  645. stream_generator = generate_rtsp_mjpeg_stream
  646. logger.info("Using RTSP protocol for %s", printer.model)
  647. # Track stream start time. Set only if absent so the value reflects when
  648. # the SHARED upstream first started streaming, not when each new viewer
  649. # attached — otherwise /camera/status would report stream_uptime jumping
  650. # backward whenever a second viewer joins. The upstream generator's
  651. # finally clears this entry when the upstream actually ends.
  652. import time
  653. _stream_start_times.setdefault(printer_id, time.time())
  654. # Fan-out broadcaster (#1089): one upstream connection per printer, shared
  655. # across all viewers. Most Bambu printers only allow a single concurrent
  656. # camera connection, so opening the same printer in two tabs would
  657. # otherwise kick the first viewer off. The broadcaster owns the single
  658. # upstream and the per-viewer disconnect handling.
  659. #
  660. # Note: the upstream's fps is fixed by the first viewer who creates the
  661. # broadcaster. Concurrent viewers share that rate; new viewers after
  662. # teardown create a fresh broadcaster at their requested fps.
  663. fanout_key = f"printer-{printer_id}"
  664. upstream_stream_id = f"{printer_id}-fanout"
  665. def _factory(disconnect_event: asyncio.Event):
  666. # Re-bind locals into the closure so the async generator below sees
  667. # them — disconnect_event is owned by the broadcaster and signalled
  668. # when the last subscriber leaves (after the grace window).
  669. return stream_generator(
  670. ip_address=printer.ip_address,
  671. access_code=printer.access_code,
  672. model=printer.model,
  673. fps=fps,
  674. stream_id=upstream_stream_id,
  675. disconnect_event=disconnect_event,
  676. printer_id=printer_id,
  677. )
  678. # Subscribe with a one-shot retry to close a tiny race: the grace-window
  679. # teardown can flip the broadcaster to `stopped=True` between the registry
  680. # lookup and our subscribe call. The retry forces the registry to mint a
  681. # fresh broadcaster (since the now-stopped one is replaced), and the second
  682. # subscribe is guaranteed to land on it before any teardown can fire.
  683. broadcaster: MjpegBroadcaster = await get_or_create_broadcaster(fanout_key, _factory)
  684. try:
  685. queue = await broadcaster.subscribe()
  686. except RuntimeError:
  687. broadcaster = await get_or_create_broadcaster(fanout_key, _factory)
  688. queue = await broadcaster.subscribe()
  689. logger.info(
  690. "Camera viewer attached to %s (subscribers=%d)",
  691. fanout_key,
  692. broadcaster.subscriber_count,
  693. )
  694. async def _is_disconnected() -> bool:
  695. try:
  696. return await request.is_disconnected()
  697. except Exception:
  698. # Older starlette/uvicorn can raise during teardown — treat that
  699. # as "client gone" so the subscriber cleanly unsubscribes.
  700. return True
  701. def _log_detach(remaining: int) -> None:
  702. logger.info("Camera viewer detached from %s (subscribers=%d)", fanout_key, remaining)
  703. async def _generate():
  704. async for chunk in iter_subscriber(
  705. broadcaster,
  706. queue,
  707. is_disconnected=_is_disconnected,
  708. on_unsubscribe=_log_detach,
  709. ):
  710. yield chunk
  711. return StreamingResponse(
  712. _generate(),
  713. media_type="multipart/x-mixed-replace; boundary=frame",
  714. headers={
  715. "Cache-Control": "no-cache, no-store, must-revalidate",
  716. "Pragma": "no-cache",
  717. "Expires": "0",
  718. },
  719. )
  720. @router.api_route("/{printer_id}/camera/stop", methods=["GET", "POST"])
  721. async def stop_camera_stream(
  722. printer_id: int,
  723. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  724. ):
  725. """Stop active camera streams for a printer.
  726. Called by the frontend on viewer unmount (cam-wall tile, embedded viewer,
  727. popup window). Accepts both GET and POST (POST for sendBeacon compatibility).
  728. Reference-count guard: every viewer of a printer subscribes to the same
  729. fan-out broadcaster, so a force-shutdown triggered by ONE leaving viewer
  730. used to kill the others' streams (cam-wall tile froze when a user opened
  731. then closed the embedded viewer). If any subscriber is still attached,
  732. skip the force-teardown — the broadcaster's natural grace-shutdown (5 s
  733. after subscribers drop to 0) handles cleanup when the leaving viewer's
  734. HTTP connection actually closes.
  735. """
  736. broadcaster_key = f"printer-{printer_id}"
  737. remaining_subscribers = get_subscriber_count(broadcaster_key)
  738. if remaining_subscribers >= 1:
  739. logger.info(
  740. "Skipping force-shutdown for printer %s: %d subscriber(s) still attached; "
  741. "natural cleanup will tear down when last viewer disconnects",
  742. printer_id,
  743. remaining_subscribers,
  744. )
  745. return {"stopped": 0, "skipped": True}
  746. stopped = 0
  747. # Tear down the fan-out broadcaster first (#1089). This cleanly notifies
  748. # all subscribed viewers and asks the upstream generator to stop
  749. # reconnecting before we fall back to forcefully killing the process below.
  750. if await shutdown_broadcaster(broadcaster_key):
  751. logger.info("Shut down camera fan-out broadcaster for printer %s", printer_id)
  752. # Stop ffmpeg/RTSP streams
  753. to_remove = []
  754. for stream_id, process in list(_active_streams.items()):
  755. if stream_id.startswith(f"{printer_id}-"):
  756. to_remove.append(stream_id)
  757. # Signal the generator to stop reconnecting BEFORE killing the process
  758. event = _disconnect_events.get(stream_id)
  759. if event:
  760. event.set()
  761. if process.returncode is None:
  762. # Shared helper, not an inline copy: it bounds the post-kill
  763. # wait (#2580) — a killed-but-unreaped ffmpeg used to hang this
  764. # request forever, exactly when the user hit Stop to recover a
  765. # stuck stream.
  766. await _terminate_ffmpeg(process, stream_id)
  767. stopped += 1
  768. logger.info("Terminated ffmpeg process for stream %s", stream_id)
  769. _spawned_ffmpeg_pids.pop(process.pid, None)
  770. for stream_id in to_remove:
  771. _active_streams.pop(stream_id, None)
  772. _disconnect_events.pop(stream_id, None)
  773. _stream_last_frame_times.pop(stream_id, None)
  774. # Stop chamber image streams
  775. to_remove_chamber = []
  776. for stream_id, (_reader, writer) in list(_active_chamber_streams.items()):
  777. if stream_id.startswith(f"{printer_id}-"):
  778. to_remove_chamber.append(stream_id)
  779. # Signal the generator to stop
  780. event = _disconnect_events.get(stream_id)
  781. if event:
  782. event.set()
  783. try:
  784. writer.close()
  785. stopped += 1
  786. logger.info("Closed chamber image connection for stream %s", stream_id)
  787. except OSError as e:
  788. logger.warning("Error stopping chamber stream %s: %s", stream_id, e)
  789. for stream_id in to_remove_chamber:
  790. _active_chamber_streams.pop(stream_id, None)
  791. _disconnect_events.pop(stream_id, None)
  792. _stream_last_frame_times.pop(stream_id, None)
  793. logger.info("Stopped %s camera stream(s) for printer %s", stopped, printer_id)
  794. return {"stopped": stopped}
  795. @router.get("/{printer_id}/camera/snapshot")
  796. async def camera_snapshot(
  797. printer_id: int,
  798. _: None = RequireCameraStreamTokenIfAuthEnabled,
  799. ):
  800. """Capture a single frame from the printer camera.
  801. Returns a JPEG image.
  802. Requires a stream token query param (?token=xxx) when auth is enabled.
  803. """
  804. import tempfile
  805. from pathlib import Path
  806. # Fetch the printer in a short-lived session and release the pooled DB
  807. # connection BEFORE the camera capture below (up to 15s, longer under a
  808. # saturated FTP/camera pool). Holding a Depends(get_db) session across the
  809. # grab pinned one connection per snapshot — and the cam wall polls this
  810. # per tile every 8s — so overlapping captures could pile up connections on
  811. # a large farm (issue #2572, sibling of the camera_stream fix). Everything
  812. # below reads only already-loaded scalar columns (expire_on_commit=False).
  813. async with database.async_session() as db:
  814. printer = await get_printer_or_404(printer_id, db)
  815. # Check for external camera first
  816. if printer.external_camera_enabled and printer.external_camera_url:
  817. from backend.app.services.external_camera import capture_frame
  818. frame_data = await capture_frame(
  819. printer.external_camera_url,
  820. printer.external_camera_type,
  821. timeout=15,
  822. snapshot_url=printer.external_camera_snapshot_url,
  823. )
  824. if not frame_data:
  825. raise HTTPException(
  826. status_code=503,
  827. detail="Failed to capture frame from external camera.",
  828. )
  829. return Response(
  830. content=frame_data,
  831. media_type="image/jpeg",
  832. headers={
  833. "Cache-Control": "no-cache, no-store, must-revalidate",
  834. "Content-Disposition": f'inline; filename="snapshot_{printer_id}.jpg"',
  835. },
  836. )
  837. # Reuse the fan-out broadcaster's buffered frame when a viewer is already
  838. # watching — avoids opening a second concurrent RTSP socket on printers
  839. # that allow only one camera connection (e.g. X2D firmware 01.01.00.00;
  840. # see #1271). Buffered frame is <1s old while a viewer is connected.
  841. buffered = try_get_active_buffered_frame(printer_id)
  842. if buffered:
  843. return Response(
  844. content=buffered,
  845. media_type="image/jpeg",
  846. headers={
  847. "Cache-Control": "no-cache, no-store, must-revalidate",
  848. "Content-Disposition": f'inline; filename="snapshot_{printer_id}.jpg"',
  849. },
  850. )
  851. # Create temporary file for the snapshot (0600 so only the app user can read it)
  852. fd, tmp_name = tempfile.mkstemp(suffix=".jpg")
  853. os.close(fd)
  854. temp_path = Path(tmp_name)
  855. temp_path.chmod(0o600)
  856. try:
  857. success = await capture_camera_frame(
  858. ip_address=printer.ip_address,
  859. access_code=printer.access_code,
  860. model=printer.model,
  861. output_path=temp_path,
  862. timeout=15,
  863. )
  864. if not success:
  865. raise HTTPException(
  866. status_code=503,
  867. detail="Failed to capture camera frame. Ensure printer is on and camera is enabled.",
  868. )
  869. # Read and return the image
  870. with open(temp_path, "rb") as f:
  871. image_data = f.read()
  872. return Response(
  873. content=image_data,
  874. media_type="image/jpeg",
  875. headers={
  876. "Cache-Control": "no-cache, no-store, must-revalidate",
  877. "Content-Disposition": f'inline; filename="snapshot_{printer_id}.jpg"',
  878. },
  879. )
  880. finally:
  881. # Clean up temp file
  882. if temp_path.exists():
  883. temp_path.unlink()
  884. @router.get("/{printer_id}/camera/test")
  885. async def test_camera(
  886. printer_id: int,
  887. db: AsyncSession = Depends(get_db),
  888. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  889. ):
  890. """Test camera connection for a printer.
  891. Returns success status and any error message.
  892. """
  893. printer = await get_printer_or_404(printer_id, db)
  894. result = await test_camera_connection(
  895. ip_address=printer.ip_address,
  896. access_code=printer.access_code,
  897. model=printer.model,
  898. )
  899. return result
  900. @router.post("/{printer_id}/camera/diagnose")
  901. async def diagnose_camera_route(
  902. printer_id: int,
  903. db: AsyncSession = Depends(get_db),
  904. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  905. ):
  906. """Run staged diagnostics for a printer's camera path.
  907. Returns a structured result the frontend renders inline so users can
  908. self-diagnose "connection lost" before opening a ticket. See
  909. ``camera_diagnose`` for stage details and the live-stream shortcut.
  910. """
  911. import time
  912. from backend.app.services.camera_diagnose import diagnose_camera
  913. printer = await get_printer_or_404(printer_id, db)
  914. # Look up live-stream evidence so the diagnostic can short-circuit
  915. # instead of fighting a viewer for the printer's single camera slot.
  916. has_live = is_stream_active(printer_id)
  917. last_ts = _last_frame_times.get(printer_id) if has_live else None
  918. live_age = (time.time() - last_ts) if (has_live and last_ts) else None
  919. result = await diagnose_camera(
  920. ip_address=printer.ip_address,
  921. access_code=printer.access_code,
  922. model=printer.model,
  923. printer_id=printer_id,
  924. has_live_stream=has_live,
  925. live_frame_age_seconds=live_age,
  926. )
  927. return result.to_dict()
  928. @router.get("/{printer_id}/camera/status")
  929. async def camera_status(
  930. printer_id: int,
  931. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  932. ):
  933. """Get the status of an active camera stream.
  934. Returns whether a stream is active and when the last frame was received.
  935. Used by the frontend to detect stalled streams and auto-reconnect.
  936. """
  937. import time
  938. # Check if there's an active stream for this printer
  939. has_active_stream = False
  940. # Check external camera streams
  941. if printer_id in _active_external_streams:
  942. has_active_stream = True
  943. # Check ffmpeg/RTSP streams
  944. if not has_active_stream:
  945. for stream_id in _active_streams:
  946. if stream_id.startswith(f"{printer_id}-"):
  947. process = _active_streams[stream_id]
  948. if process.returncode is None:
  949. has_active_stream = True
  950. break
  951. # Check chamber image streams
  952. if not has_active_stream:
  953. for stream_id in _active_chamber_streams:
  954. if stream_id.startswith(f"{printer_id}-"):
  955. has_active_stream = True
  956. break
  957. # Get timing information
  958. current_time = time.time()
  959. last_frame_time = _last_frame_times.get(printer_id)
  960. stream_start_time = _stream_start_times.get(printer_id)
  961. # Calculate seconds since last frame
  962. seconds_since_frame = None
  963. if last_frame_time is not None:
  964. seconds_since_frame = current_time - last_frame_time
  965. # Calculate stream uptime
  966. stream_uptime = None
  967. if stream_start_time is not None:
  968. stream_uptime = current_time - stream_start_time
  969. return {
  970. "active": has_active_stream,
  971. "has_frames": printer_id in _last_frames,
  972. "seconds_since_frame": seconds_since_frame,
  973. "stream_uptime": stream_uptime,
  974. # Consider stalled if no frame for more than 10 seconds after stream started
  975. "stalled": (
  976. has_active_stream
  977. and stream_uptime is not None
  978. and stream_uptime > 5 # Give 5 seconds for stream to start
  979. and (seconds_since_frame is None or seconds_since_frame > 10)
  980. ),
  981. }
  982. @router.post("/{printer_id}/camera/external/test")
  983. async def test_external_camera(
  984. printer_id: int,
  985. url: str,
  986. camera_type: str,
  987. db: AsyncSession = Depends(get_db),
  988. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  989. ):
  990. """Test external camera connection.
  991. Args:
  992. printer_id: Printer ID (for authorization)
  993. url: Camera URL or USB device path to test
  994. camera_type: Camera type ("mjpeg", "rtsp", "snapshot", "usb")
  995. Returns:
  996. Dict with {success: bool, error?: str, resolution?: str}
  997. """
  998. # Verify printer exists (for authorization)
  999. await get_printer_or_404(printer_id, db)
  1000. from backend.app.services.external_camera import test_connection
  1001. return await test_connection(url, camera_type)
  1002. @router.get("/{printer_id}/camera/check-plate")
  1003. async def check_plate_empty(
  1004. printer_id: int,
  1005. plate_type: str | None = None,
  1006. use_external: bool | None = None,
  1007. include_debug_image: bool = False,
  1008. db: AsyncSession = Depends(get_db),
  1009. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  1010. ):
  1011. """Check if the build plate is empty using camera vision.
  1012. Uses calibration-based difference detection - compares current frame
  1013. to a reference image of the empty plate.
  1014. IMPORTANT: Chamber light must be ON for reliable detection.
  1015. Args:
  1016. printer_id: Printer ID
  1017. plate_type: Type of build plate (e.g., "High Temp Plate") for calibration lookup
  1018. use_external: If True, prefer external camera over built-in. When omitted
  1019. (None), defaults to the printer's external_camera_enabled setting —
  1020. mirroring the runtime auto-check at print start (main.py). Without
  1021. this default the UI's manual check would always use the built-in
  1022. camera, mismatching the reference saved during calibration (#1359).
  1023. include_debug_image: If True, return URL to annotated debug image
  1024. Returns:
  1025. Dict with detection results:
  1026. - is_empty: bool - Whether plate appears empty
  1027. - confidence: float - Confidence level (0.0 to 1.0)
  1028. - difference_percent: float - How different from calibration reference
  1029. - message: str - Human-readable result message
  1030. - needs_calibration: bool - True if calibration is required
  1031. - light_warning: bool - True if chamber light is off
  1032. """
  1033. from backend.app.services.plate_detection import (
  1034. check_plate_empty as do_check,
  1035. is_plate_detection_available,
  1036. )
  1037. from backend.app.services.printer_manager import printer_manager
  1038. # Check printer exists first (before OpenCV check)
  1039. printer = await get_printer_or_404(printer_id, db)
  1040. if use_external is None:
  1041. use_external = bool(
  1042. printer.external_camera_enabled and printer.external_camera_url and printer.external_camera_type
  1043. )
  1044. if not is_plate_detection_available():
  1045. raise HTTPException(
  1046. status_code=503,
  1047. detail="Plate detection not available. Install opencv-python-headless to enable.",
  1048. )
  1049. # Check chamber light status
  1050. light_warning = False
  1051. state = printer_manager.get_status(printer_id)
  1052. if state and not state.chamber_light:
  1053. light_warning = True
  1054. from backend.app.services.plate_detection import PlateDetector
  1055. # Build ROI tuple from printer settings if available
  1056. roi = None
  1057. if all(
  1058. [
  1059. printer.plate_detection_roi_x is not None,
  1060. printer.plate_detection_roi_y is not None,
  1061. printer.plate_detection_roi_w is not None,
  1062. printer.plate_detection_roi_h is not None,
  1063. ]
  1064. ):
  1065. roi = (
  1066. printer.plate_detection_roi_x,
  1067. printer.plate_detection_roi_y,
  1068. printer.plate_detection_roi_w,
  1069. printer.plate_detection_roi_h,
  1070. )
  1071. result = await do_check(
  1072. printer_id=printer.id,
  1073. ip_address=printer.ip_address,
  1074. access_code=printer.access_code,
  1075. model=printer.model,
  1076. plate_type=plate_type,
  1077. include_debug_image=include_debug_image,
  1078. external_camera_url=printer.external_camera_url if printer.external_camera_enabled else None,
  1079. external_camera_type=printer.external_camera_type if printer.external_camera_enabled else None,
  1080. use_external=use_external,
  1081. roi=roi,
  1082. external_camera_snapshot_url=printer.external_camera_snapshot_url if printer.external_camera_enabled else None,
  1083. )
  1084. # Get reference count for the response
  1085. detector = PlateDetector()
  1086. ref_count = detector.get_calibration_count(printer.id)
  1087. response = result.to_dict()
  1088. response["light_warning"] = light_warning
  1089. response["reference_count"] = ref_count
  1090. response["max_references"] = detector.MAX_REFERENCES
  1091. # Include current ROI in response
  1092. if roi:
  1093. response["roi"] = {"x": roi[0], "y": roi[1], "w": roi[2], "h": roi[3]}
  1094. else:
  1095. # Return default ROI
  1096. response["roi"] = {"x": 0.15, "y": 0.35, "w": 0.70, "h": 0.55}
  1097. # If debug image requested and available, encode as base64 data URL
  1098. if include_debug_image and result.debug_image:
  1099. import base64
  1100. b64_image = base64.b64encode(result.debug_image).decode("utf-8")
  1101. response["debug_image_url"] = f"data:image/jpeg;base64,{b64_image}"
  1102. return response
  1103. @router.post("/{printer_id}/camera/plate-detection/calibrate")
  1104. async def calibrate_plate_detection(
  1105. printer_id: int,
  1106. label: str | None = None,
  1107. use_external: bool | None = None,
  1108. db: AsyncSession = Depends(get_db),
  1109. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  1110. ):
  1111. """Calibrate plate detection by capturing a reference image of the empty plate.
  1112. The plate MUST be empty when calling this endpoint. The captured image
  1113. will be used as the reference for future detection comparisons.
  1114. Supports up to 5 reference images per printer. When adding a 6th, the oldest
  1115. is automatically removed.
  1116. IMPORTANT: Chamber light should be ON for calibration.
  1117. Args:
  1118. printer_id: Printer ID
  1119. label: Optional label for this reference (e.g., "High Temp Plate", "Wham Bam")
  1120. use_external: If True, prefer external camera over built-in. When omitted
  1121. (None), defaults to the printer's external_camera_enabled setting so
  1122. calibration captures from the same source the runtime auto-check
  1123. uses at print start (#1359).
  1124. Returns:
  1125. Dict with:
  1126. - success: bool - Whether calibration succeeded
  1127. - message: str - Status message
  1128. - index: int - The reference slot used (0-4)
  1129. """
  1130. from backend.app.services.plate_detection import (
  1131. calibrate_plate,
  1132. is_plate_detection_available,
  1133. )
  1134. from backend.app.services.printer_manager import printer_manager
  1135. # Check printer exists first (before OpenCV check)
  1136. printer = await get_printer_or_404(printer_id, db)
  1137. if use_external is None:
  1138. use_external = bool(
  1139. printer.external_camera_enabled and printer.external_camera_url and printer.external_camera_type
  1140. )
  1141. if not is_plate_detection_available():
  1142. raise HTTPException(
  1143. status_code=503,
  1144. detail="Plate detection not available. Install opencv-python-headless to enable.",
  1145. )
  1146. # Check chamber light - warn but don't block
  1147. state = printer_manager.get_status(printer_id)
  1148. light_warning = state and not state.chamber_light
  1149. success, message, index = await calibrate_plate(
  1150. printer_id=printer.id,
  1151. ip_address=printer.ip_address,
  1152. access_code=printer.access_code,
  1153. model=printer.model,
  1154. label=label,
  1155. external_camera_url=printer.external_camera_url if printer.external_camera_enabled else None,
  1156. external_camera_type=printer.external_camera_type if printer.external_camera_enabled else None,
  1157. use_external=use_external,
  1158. external_camera_snapshot_url=printer.external_camera_snapshot_url if printer.external_camera_enabled else None,
  1159. )
  1160. if light_warning and success:
  1161. message += " (Warning: Chamber light was off)"
  1162. return {"success": success, "message": message, "index": index}
  1163. @router.delete("/{printer_id}/camera/plate-detection/calibrate")
  1164. async def delete_plate_calibration(
  1165. printer_id: int,
  1166. plate_type: str | None = None,
  1167. db: AsyncSession = Depends(get_db),
  1168. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  1169. ):
  1170. """Delete the plate detection calibration for a printer and plate type.
  1171. Args:
  1172. printer_id: Printer ID
  1173. plate_type: Type of build plate (if None, deletes legacy non-plate-specific calibration)
  1174. Returns:
  1175. Dict with:
  1176. - success: bool - Whether deletion succeeded
  1177. - message: str - Status message
  1178. """
  1179. from backend.app.services.plate_detection import (
  1180. delete_calibration,
  1181. is_plate_detection_available,
  1182. )
  1183. # Verify printer exists first (before OpenCV check)
  1184. await get_printer_or_404(printer_id, db)
  1185. if not is_plate_detection_available():
  1186. raise HTTPException(
  1187. status_code=503,
  1188. detail="Plate detection not available. Install opencv-python-headless to enable.",
  1189. )
  1190. deleted = delete_calibration(printer_id, plate_type)
  1191. plate_msg = f" for '{plate_type}'" if plate_type else ""
  1192. return {
  1193. "success": deleted,
  1194. "message": f"Calibration deleted{plate_msg}" if deleted else f"No calibration found{plate_msg}",
  1195. }
  1196. @router.get("/{printer_id}/camera/plate-detection/status")
  1197. async def get_plate_detection_status(
  1198. printer_id: int,
  1199. plate_type: str | None = None,
  1200. db: AsyncSession = Depends(get_db),
  1201. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  1202. ):
  1203. """Check plate detection status for a printer and plate type.
  1204. Returns:
  1205. Dict with:
  1206. - available: bool - Whether OpenCV is installed
  1207. - calibrated: bool - Whether printer has calibration for this plate type
  1208. - plate_type: str - The plate type queried
  1209. - chamber_light: bool - Whether chamber light is on
  1210. - message: str - Status message
  1211. """
  1212. from backend.app.services.plate_detection import (
  1213. get_calibration_status,
  1214. is_plate_detection_available,
  1215. )
  1216. from backend.app.services.printer_manager import printer_manager
  1217. # Verify printer exists first (before OpenCV check)
  1218. await get_printer_or_404(printer_id, db)
  1219. if not is_plate_detection_available():
  1220. return {
  1221. "available": False,
  1222. "calibrated": False,
  1223. "plate_type": plate_type,
  1224. "chamber_light": False,
  1225. "message": "OpenCV not installed",
  1226. }
  1227. # Get chamber light status
  1228. state = printer_manager.get_status(printer_id)
  1229. chamber_light = state.chamber_light if state else False
  1230. status = get_calibration_status(printer_id, plate_type)
  1231. status["chamber_light"] = chamber_light
  1232. return status
  1233. @router.get("/{printer_id}/camera/plate-detection/references")
  1234. async def get_plate_references(
  1235. printer_id: int,
  1236. db: AsyncSession = Depends(get_db),
  1237. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  1238. ):
  1239. """Get all calibration references for a printer with metadata.
  1240. Returns list of references with index, label, timestamp, and thumbnail URL.
  1241. """
  1242. from backend.app.services.plate_detection import PlateDetector, is_plate_detection_available
  1243. # Verify printer exists first (before OpenCV check)
  1244. await get_printer_or_404(printer_id, db)
  1245. if not is_plate_detection_available():
  1246. raise HTTPException(503, "Plate detection not available")
  1247. detector = PlateDetector()
  1248. references = detector.get_references(printer_id)
  1249. # Add thumbnail URLs
  1250. for ref in references:
  1251. ref["thumbnail_url"] = (
  1252. f"/api/v1/printers/{printer_id}/camera/plate-detection/references/{ref['index']}/thumbnail"
  1253. )
  1254. return {
  1255. "references": references,
  1256. "max_references": detector.MAX_REFERENCES,
  1257. }
  1258. @router.get("/{printer_id}/camera/plate-detection/references/{index}/thumbnail")
  1259. async def get_reference_thumbnail(
  1260. printer_id: int,
  1261. index: int,
  1262. db: AsyncSession = Depends(get_db),
  1263. _: None = RequireCameraStreamTokenIfAuthEnabled,
  1264. ):
  1265. """Get thumbnail image for a calibration reference.
  1266. Requires a stream token query param (?token=xxx) when auth is enabled.
  1267. """
  1268. from fastapi.responses import Response
  1269. from backend.app.services.plate_detection import PlateDetector, is_plate_detection_available
  1270. # Verify printer exists first (before OpenCV check)
  1271. await get_printer_or_404(printer_id, db)
  1272. if not is_plate_detection_available():
  1273. raise HTTPException(503, "Plate detection not available")
  1274. detector = PlateDetector()
  1275. thumbnail = detector.get_reference_thumbnail(printer_id, index)
  1276. if thumbnail is None:
  1277. raise HTTPException(404, "Reference not found")
  1278. return Response(content=thumbnail, media_type="image/jpeg")
  1279. @router.put("/{printer_id}/camera/plate-detection/references/{index}")
  1280. async def update_reference_label(
  1281. printer_id: int,
  1282. index: int,
  1283. label: str,
  1284. db: AsyncSession = Depends(get_db),
  1285. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  1286. ):
  1287. """Update the label for a calibration reference."""
  1288. from backend.app.services.plate_detection import PlateDetector, is_plate_detection_available
  1289. # Verify printer exists first (before OpenCV check)
  1290. await get_printer_or_404(printer_id, db)
  1291. if not is_plate_detection_available():
  1292. raise HTTPException(503, "Plate detection not available")
  1293. detector = PlateDetector()
  1294. success = detector.update_reference_label(printer_id, index, label)
  1295. if not success:
  1296. raise HTTPException(404, "Reference not found")
  1297. return {"success": True, "index": index, "label": label}
  1298. @router.delete("/{printer_id}/camera/plate-detection/references/{index}")
  1299. async def delete_reference(
  1300. printer_id: int,
  1301. index: int,
  1302. db: AsyncSession = Depends(get_db),
  1303. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  1304. ):
  1305. """Delete a specific calibration reference."""
  1306. from backend.app.services.plate_detection import PlateDetector, is_plate_detection_available
  1307. # Verify printer exists first (before OpenCV check)
  1308. await get_printer_or_404(printer_id, db)
  1309. if not is_plate_detection_available():
  1310. raise HTTPException(503, "Plate detection not available")
  1311. detector = PlateDetector()
  1312. success = detector.delete_reference(printer_id, index)
  1313. if not success:
  1314. raise HTTPException(404, "Reference not found")
  1315. return {"success": True, "message": "Reference deleted"}
  1316. def _scan_bambu_ffmpeg_pids() -> list[int]:
  1317. """Scan /proc for ffmpeg processes that are ours.
  1318. Two shapes are matched, both unambiguously Bambuddy's:
  1319. - Bambu RTSP: no other software connects to ``rtsp(s)://bblp:``.
  1320. - External USB (V4L2): an ffmpeg spawned with ``-f v4l2`` is our USB camera
  1321. stream (#2675). Only orphans are killed — the caller excludes PIDs still in
  1322. ``_active_streams``, so a live USB stream (now registered there) is spared.
  1323. This catches orphans that survive app restarts and are not in any tracking dict.
  1324. """
  1325. import os
  1326. pids = []
  1327. try:
  1328. for entry in os.listdir("/proc"):
  1329. if not entry.isdigit():
  1330. continue
  1331. try:
  1332. with open(f"/proc/{entry}/cmdline", "rb") as f:
  1333. cmdline = f.read()
  1334. if b"ffmpeg" not in cmdline:
  1335. continue
  1336. # Match both rtsp:// (via TLS proxy) and rtsps:// (direct), plus
  1337. # the `-f v4l2` input flag our USB camera command always carries.
  1338. if b"rtsp://bblp:" in cmdline or b"rtsps://bblp:" in cmdline or b"v4l2" in cmdline:
  1339. pids.append(int(entry))
  1340. except (OSError, PermissionError, ValueError):
  1341. continue
  1342. except OSError:
  1343. pass
  1344. return pids
  1345. async def cleanup_orphaned_streams():
  1346. """Clean up orphaned ffmpeg processes and stale stream entries.
  1347. Called periodically from the background task loop in main.py.
  1348. Three-layer cleanup:
  1349. 1. /proc scan — finds ALL Bambu ffmpeg processes on the system, even those
  1350. from previous app sessions. This is the nuclear safety net.
  1351. 2. _spawned_ffmpeg_pids — tracks PIDs spawned this session, catches orphans
  1352. that were removed from _active_streams but not killed.
  1353. 3. _active_streams — kills stale entries with no recent frames.
  1354. """
  1355. import os
  1356. import signal
  1357. import time
  1358. cleaned = 0
  1359. now = time.time()
  1360. # Collect PIDs that are legitimately in-use (active stream, process alive)
  1361. active_pids = {proc.pid for proc in _active_streams.values() if proc.returncode is None}
  1362. # Also exclude PIDs from one-shot snapshot captures (Obico detection, finish photos, etc.)
  1363. from backend.app.services.camera import _active_capture_pids
  1364. active_pids |= _active_capture_pids
  1365. # 1. /proc scan — catch ALL orphaned Bambu ffmpeg processes on the system.
  1366. # Any ffmpeg with rtsp(s)://bblp: that is NOT in an active stream is orphaned.
  1367. for pid in _scan_bambu_ffmpeg_pids():
  1368. if pid in active_pids:
  1369. continue
  1370. logger.info("Killing orphaned ffmpeg process found via /proc (pid=%d)", pid)
  1371. try:
  1372. os.kill(pid, signal.SIGKILL)
  1373. except (ProcessLookupError, OSError):
  1374. pass
  1375. _spawned_ffmpeg_pids.pop(pid, None)
  1376. cleaned += 1
  1377. # 2. Clean up _spawned_ffmpeg_pids entries for dead processes
  1378. for pid in list(_spawned_ffmpeg_pids):
  1379. try:
  1380. os.kill(pid, 0) # existence check
  1381. except (ProcessLookupError, OSError):
  1382. _spawned_ffmpeg_pids.pop(pid, None)
  1383. # 3. Clean up _active_streams entries with dead processes
  1384. dead_streams = [sid for sid, proc in _active_streams.items() if proc.returncode is not None]
  1385. for sid in dead_streams:
  1386. proc = _active_streams.pop(sid, None)
  1387. if proc:
  1388. _spawned_ffmpeg_pids.pop(proc.pid, None)
  1389. cleaned += 1
  1390. # 4. Kill stale active streams (alive but no frames for >30s)
  1391. # Uses per-stream timestamps to avoid false "fresh" readings from newer streams
  1392. for sid, proc in list(_active_streams.items()):
  1393. if proc.returncode is not None:
  1394. continue
  1395. # Per-stream frame time is authoritative; fall back to per-printer
  1396. stream_last_frame = _stream_last_frame_times.get(sid)
  1397. if stream_last_frame is None:
  1398. try:
  1399. printer_id = int(sid.split("-", 1)[0])
  1400. except (ValueError, IndexError):
  1401. continue
  1402. stream_last_frame = _last_frame_times.get(printer_id)
  1403. spawn_time = _spawned_ffmpeg_pids.get(proc.pid, now)
  1404. if stream_last_frame is None:
  1405. stream_last_frame = spawn_time
  1406. if now - spawn_time > 60 and now - stream_last_frame > 30:
  1407. logger.info("Killing stale ffmpeg stream %s (no frames for %.0fs)", sid, now - stream_last_frame)
  1408. # Signal the generator to stop reconnecting
  1409. event = _disconnect_events.get(sid)
  1410. if event:
  1411. event.set()
  1412. try:
  1413. proc.kill()
  1414. # Bounded (#2580): an unreaped SIGKILLed ffmpeg must not hang
  1415. # the periodic cleanup loop — this janitor is the safety net
  1416. # that recovers stalled streams, so it can least afford to
  1417. # block. The /proc scan above retries the kill next pass.
  1418. await asyncio.wait_for(proc.wait(), timeout=_FFMPEG_KILL_TIMEOUT)
  1419. except (ProcessLookupError, OSError):
  1420. pass
  1421. except TimeoutError:
  1422. logger.error(
  1423. "ffmpeg (pid=%d) did not exit within %.1fs of SIGKILL; abandoning wait (stream_id=%s)",
  1424. proc.pid,
  1425. _FFMPEG_KILL_TIMEOUT,
  1426. sid,
  1427. )
  1428. _active_streams.pop(sid, None)
  1429. _disconnect_events.pop(sid, None)
  1430. _stream_last_frame_times.pop(sid, None)
  1431. _spawned_ffmpeg_pids.pop(proc.pid, None)
  1432. cleaned += 1
  1433. # 4. Clean stale chamber stream entries
  1434. dead_chamber = [sid for sid, (_reader, writer) in _active_chamber_streams.items() if writer.is_closing()]
  1435. for sid in dead_chamber:
  1436. _active_chamber_streams.pop(sid, None)
  1437. cleaned += 1
  1438. if cleaned:
  1439. logger.info("Cleaned up %d orphaned camera stream(s)", cleaned)