camera.py 82 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047
  1. """Camera streaming API endpoints for Bambu Lab printers."""
  2. import asyncio
  3. import contextlib
  4. import logging
  5. import os
  6. import subprocess
  7. import sys
  8. import time
  9. import uuid
  10. import zlib
  11. from collections.abc import AsyncGenerator
  12. from fastapi import APIRouter, Depends, HTTPException, Request
  13. from fastapi.responses import Response, StreamingResponse
  14. from sqlalchemy import select
  15. from sqlalchemy.ext.asyncio import AsyncSession
  16. from backend.app.core import database
  17. from backend.app.core.auth import (
  18. RequireCameraStreamTokenIfAuthEnabled,
  19. RequirePermissionIfAuthEnabled,
  20. create_camera_stream_token,
  21. )
  22. from backend.app.core.database import get_db
  23. from backend.app.core.permissions import Permission
  24. from backend.app.models.printer import Printer
  25. from backend.app.models.user import User
  26. from backend.app.services.camera import (
  27. capture_camera_frame,
  28. close_tls_proxy,
  29. create_tls_proxy,
  30. generate_chamber_image_stream,
  31. get_camera_port,
  32. get_ffmpeg_path,
  33. is_chamber_image_model,
  34. read_next_chamber_frame,
  35. rtsp_socket_timeout_flag,
  36. test_camera_connection,
  37. )
  38. from backend.app.services.camera_fanout import (
  39. MjpegBroadcaster,
  40. get_or_create_broadcaster,
  41. get_subscriber_count,
  42. iter_subscriber,
  43. shutdown_broadcaster,
  44. )
  45. from backend.app.services.camera_profiles import get_camera_profile
  46. from backend.app.utils.ffmpeg_output import summarize_ffmpeg_stderr
  47. logger = logging.getLogger(__name__)
  48. router = APIRouter(prefix="/printers", tags=["camera"])
  49. # Grace period for a SIGTERMed ffmpeg to shut down before we SIGKILL it. Only
  50. # reachable when ffmpeg genuinely ignores SIGTERM: _terminate_ffmpeg drains the
  51. # pipes first, and a drained ffmpeg exits in ~0.15s.
  52. _FFMPEG_TERM_TIMEOUT = 2.0
  53. # Upper bound on waiting for a SIGKILLed ffmpeg to be reaped (#2580).
  54. #
  55. # The original diagnosis — "a killed ffmpeg stuck in uninterruptible I/O on a
  56. # dead RTSP socket" — was wrong, and this bound was capping a deadlock of our
  57. # own making rather than waiting out a stuck process. A process that survives
  58. # SIGKILL would have to be in uninterruptible sleep (state D); the ffmpeg seen
  59. # doing this was in state S, and its returncode was already set to -9 while
  60. # wait() was still blocked. The real cause was undrained pipes (see
  61. # _terminate_ffmpeg), which made this timeout fire on *every* camera close.
  62. #
  63. # Kept as a backstop now that the cause is fixed: it should no longer be
  64. # reachable, and if it ever is, abandoning the wait is still safe because
  65. # cleanup_orphaned_streams' /proc scan reaps any Bambu ffmpeg not attached to
  66. # an active stream on its next pass.
  67. _FFMPEG_KILL_TIMEOUT = 2.0
  68. # How long an RTSP stream may keep emitting byte-identical JPEGs before the
  69. # ffmpeg behind it is restarted (#3218). A dead upstream can leave ffmpeg
  70. # repeating its last frame indefinitely: measured on a P2S, ~29 fps of one
  71. # frame for two hours with no socket to the printer left at all, while every
  72. # check that counts frames saw a healthy stream. A live camera practically
  73. # never repeats a frame byte for byte -- sensor noise changes every one (2262
  74. # of 2262 distinct on an idle X1C chamber, #3189) -- so a run this long means
  75. # the picture is frozen.
  76. _RTSP_FROZEN_SECONDS = 20.0
  77. # "Practically never" is not never: a dark, idle chamber can encode to the same
  78. # frame every time. When the first frame after such a restart is the frozen one
  79. # again, the camera really is showing that picture, and the stream only
  80. # re-checks at this much longer interval until the picture changes -- so a
  81. # still scene costs one reconnect every few minutes instead of every 20 s, and a
  82. # real freeze on it is still recovered.
  83. _RTSP_STILL_RECHECK_SECONDS = 300.0
  84. # Track active ffmpeg processes for cleanup
  85. _active_streams: dict[str, asyncio.subprocess.Process] = {}
  86. # Track active chamber image connections for cleanup
  87. _active_chamber_streams: dict[str, tuple] = {}
  88. # Store last frame for each printer (for photo capture from active stream)
  89. _last_frames: dict[int, bytes] = {}
  90. # Track last frame timestamp for each printer (for stall detection)
  91. _last_frame_times: dict[int, float] = {}
  92. # Track stream start times for each printer
  93. _stream_start_times: dict[int, float] = {}
  94. # Track active external camera streams by printer ID
  95. _active_external_streams: set[int] = set()
  96. # Track ALL spawned ffmpeg PIDs (persists even if _active_streams entries are removed)
  97. # Maps PID -> spawn timestamp — used by cleanup to find truly orphaned OS processes
  98. _spawned_ffmpeg_pids: dict[int, float] = {}
  99. # Track disconnect events per stream_id — allows stop endpoint and cleanup
  100. # to signal generators to stop reconnecting instead of just killing the process
  101. _disconnect_events: dict[str, asyncio.Event] = {}
  102. # Track last frame time per stream_id (not just per printer_id) for stale detection
  103. _stream_last_frame_times: dict[str, float] = {}
  104. # How much of a streaming ffmpeg's stderr to retain: enough for the input
  105. # analysis plus a burst of errors, capped so a long-running stream can't grow it.
  106. _FFMPEG_STDERR_TAIL_BYTES = 16384
  107. # Live stderr collectors by pid — see _FfmpegStderrTail. Present means "this
  108. # process's stderr already has a reader; do not open a second one".
  109. _stderr_tails: dict[int, "_FfmpegStderrTail"] = {}
  110. def get_buffered_frame(printer_id: int) -> bytes | None:
  111. """Get the last buffered frame for a printer from an active stream.
  112. Returns the JPEG frame data if available, or None if no active stream.
  113. """
  114. return _last_frames.get(printer_id)
  115. def is_stream_active(printer_id: int) -> bool:
  116. """Return True iff a fan-out camera stream is currently registered for this printer.
  117. Snapshot callers (Obico polling, manual /camera/snapshot) MUST NOT open a
  118. second concurrent RTSP/chamber-image socket while a viewer is attached:
  119. most Bambu firmwares allow only one camera connection, so the competing
  120. socket either kicks the live viewer off or gets refused itself, and the
  121. resulting reconnect storm tears down the fan-out broadcaster (see #1348).
  122. Callers should consult this BEFORE trying to open a fresh socket and skip
  123. the capture cycle when it returns True — even if try_get_active_buffered_frame
  124. returns None (the stream may be running but the first frame hasn't landed
  125. in the buffer yet, or the upstream is mid-reconnect).
  126. """
  127. return any(k.startswith(f"{printer_id}-") for k in _active_streams) or any(
  128. k.startswith(f"{printer_id}-") for k in _active_chamber_streams
  129. )
  130. def try_get_active_buffered_frame(printer_id: int) -> bytes | None:
  131. """Return a buffered frame iff a stream is currently running for this printer.
  132. Snapshot callers (Obico polling, manual /camera/snapshot) tap the fan-out
  133. broadcaster's running upstream instead of opening a second concurrent
  134. RTSP/chamber-image socket. Critical for printers that allow only one
  135. camera connection (e.g. X2D firmware 01.01.00.00; see #1271).
  136. Returns None when no broadcaster is active for this printer, so callers
  137. fall through to their existing fresh-socket path unchanged.
  138. NB: returning None does NOT mean "safe to open a fresh socket" — it also
  139. fires when the stream is registered but no frame has been buffered yet
  140. (startup race, mid-reconnect). Callers that must avoid competing sockets
  141. should consult is_stream_active() first; see #1348.
  142. """
  143. if not is_stream_active(printer_id):
  144. return None
  145. return _last_frames.get(printer_id)
  146. async def get_printer_or_404(printer_id: int, db: AsyncSession) -> Printer:
  147. """Get printer by ID or raise 404."""
  148. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  149. printer = result.scalar_one_or_none()
  150. if not printer:
  151. raise HTTPException(status_code=404, detail="Printer not found")
  152. return printer
  153. async def generate_chamber_mjpeg_stream(
  154. ip_address: str,
  155. access_code: str,
  156. model: str | None,
  157. fps: int = 5,
  158. stream_id: str | None = None,
  159. disconnect_event: asyncio.Event | None = None,
  160. printer_id: int | None = None,
  161. ) -> AsyncGenerator[bytes, None]:
  162. """Generate MJPEG stream from A1/P1 printer using chamber image protocol.
  163. This connects to port 6000 and reads JPEG frames using the Bambu binary protocol.
  164. """
  165. logger.info("Starting chamber image stream for %s (stream_id=%s, model=%s)", ip_address, stream_id, model)
  166. # Register disconnect event so stop endpoint can signal us
  167. if stream_id and disconnect_event:
  168. _disconnect_events[stream_id] = disconnect_event
  169. connection = await generate_chamber_image_stream(ip_address, access_code, fps)
  170. if connection is None:
  171. logger.error("Failed to connect to chamber image stream for %s", ip_address)
  172. yield (
  173. b"--frame\r\n"
  174. b"Content-Type: text/plain\r\n\r\n"
  175. b"Error: Camera connection failed. Check printer is on and camera is enabled.\r\n"
  176. )
  177. return
  178. reader, writer = connection
  179. # Track active connection for cleanup
  180. if stream_id:
  181. _active_chamber_streams[stream_id] = (reader, writer)
  182. try:
  183. frame_interval = 1.0 / fps if fps > 0 else 0.2
  184. last_frame_time = 0.0
  185. while True:
  186. # Check if client disconnected
  187. if disconnect_event and disconnect_event.is_set():
  188. logger.info("Client disconnected, stopping chamber stream %s", stream_id)
  189. break
  190. # Read next frame
  191. frame = await read_next_chamber_frame(reader, timeout=30.0)
  192. if frame is None:
  193. logger.warning("Chamber image stream ended for %s", stream_id)
  194. break
  195. # Save frame to buffer for photo capture and track timestamp
  196. if printer_id is not None:
  197. _last_frames[printer_id] = frame
  198. _last_frame_times[printer_id] = time.time()
  199. # Rate limiting - skip frames if needed to maintain target FPS
  200. current_time = asyncio.get_event_loop().time()
  201. if current_time - last_frame_time < frame_interval:
  202. continue
  203. last_frame_time = current_time
  204. # Yield frame in MJPEG format
  205. yield (
  206. b"--frame\r\n"
  207. b"Content-Type: image/jpeg\r\n"
  208. b"Content-Length: " + str(len(frame)).encode() + b"\r\n"
  209. b"\r\n" + frame + b"\r\n"
  210. )
  211. except asyncio.CancelledError:
  212. logger.info("Chamber image stream cancelled (stream_id=%s)", stream_id)
  213. except GeneratorExit:
  214. logger.info("Chamber image stream generator exit (stream_id=%s)", stream_id)
  215. except Exception as e:
  216. logger.exception("Chamber image stream error: %s", e)
  217. finally:
  218. # Remove from active streams and disconnect events
  219. if stream_id:
  220. _active_chamber_streams.pop(stream_id, None)
  221. _disconnect_events.pop(stream_id, None)
  222. _stream_last_frame_times.pop(stream_id, None)
  223. # Clean up frame buffer and timestamps
  224. _release_printer_frame_state(printer_id)
  225. # Close the connection
  226. try:
  227. writer.close()
  228. await writer.wait_closed()
  229. except OSError:
  230. pass # Connection already closed or broken; cleanup is best-effort
  231. logger.info("Chamber image stream stopped for %s (stream_id=%s)", ip_address, stream_id)
  232. def _new_fanout_stream_id(printer_id: int) -> str:
  233. """Registry key for one fan-out stream INSTANCE, not for the printer.
  234. A plain ``f"{printer_id}-fanout"`` meant every successive stream for a
  235. printer shared one key, so a departing generator's cleanup removed the entry
  236. its successor had just registered. The external-camera path already carries a
  237. per-instance suffix for exactly this reason (#2675); this gives the fan-out
  238. path the same property.
  239. The ``f"{printer_id}-"`` prefix is load-bearing — ``is_stream_active``,
  240. ``stop_camera_stream`` and ``/camera/status`` all find a printer's streams by
  241. scanning for it — so the suffix goes on the end.
  242. """
  243. return f"{printer_id}-fanout-{uuid.uuid4().hex[:8]}"
  244. def live_frame_for_capture(printer_id: int) -> tuple[bool, bytes | None]:
  245. """Should a one-shot capture stand down for the live view, and to what frame?
  246. Returns ``(defer, frame)``. ``defer`` True means DO NOT open a capture of
  247. your own: use ``frame`` when it isn't None, and otherwise skip this attempt
  248. rather than competing.
  249. Both camera kinds allow exactly one reader — Bambu firmware permits one
  250. connection, and a USB camera permits one V4L2 handle — so a capture that
  251. races the live view doesn't degrade, it fails outright. #2707 measured 0 of
  252. 87 and 0 of 105 layer-timelapse captures on prints watched throughout, and
  253. finish photos going out with no image attached.
  254. Skipping when the buffer is momentarily empty (stream starting, mid-
  255. reconnect) rather than falling through to a capture is the #1348 rule:
  256. opening a competing handle kicks the viewer off, which is a worse outcome
  257. than missing one frame.
  258. """
  259. if not is_stream_active(printer_id):
  260. return False, None
  261. return True, _last_frames.get(printer_id)
  262. def _release_printer_frame_state(printer_id: int | None) -> None:
  263. """Drop a printer's buffered frame and timings — unless a stream still owns them.
  264. These three dicts are keyed by printer, not by stream, so a departing
  265. generator must not clear them while a newer stream for the same printer is
  266. running. That used to happen routinely: stream ids were per-printer, so a
  267. predecessor's cleanup wiped its successor's state, leaving
  268. ``is_stream_active()`` False with a viewer attached (which is exactly what
  269. the #1348 / #1271 guards read before deciding whether it is safe to open a
  270. second camera connection), the janitor free to reap the live ffmpeg as an
  271. orphan, and snapshots without a frame to reuse.
  272. Call this AFTER removing the departing stream's own key, so the check
  273. reports on other streams rather than on the caller.
  274. """
  275. if printer_id is None or is_stream_active(printer_id):
  276. return
  277. _last_frames.pop(printer_id, None)
  278. _last_frame_times.pop(printer_id, None)
  279. _stream_start_times.pop(printer_id, None)
  280. async def _drain_pipe(reader) -> None:
  281. """Read a subprocess pipe to EOF and discard, so it can never block.
  282. Best-effort by design: any read failure means we cannot drain further, and
  283. the caller is tearing the process down regardless.
  284. """
  285. if reader is None:
  286. return
  287. try:
  288. while await reader.read(65536):
  289. pass
  290. except asyncio.CancelledError:
  291. raise
  292. except Exception: # noqa: BLE001 — teardown must not fail on a dying pipe
  293. return
  294. async def _terminate_ffmpeg(process: asyncio.subprocess.Process, stream_id: str | None = None) -> None:
  295. """Terminate an ffmpeg process gracefully, then kill if needed.
  296. Drains stdout/stderr throughout, which is load-bearing rather than hygiene.
  297. ffmpeg is spawned with both as pipes, and every caller of this has already
  298. stopped reading stdout — so by the time we get here ffmpeg is typically
  299. blocked in write() on a full 64 KiB pipe. Two things then go wrong:
  300. * SIGTERM cannot be acted on. ffmpeg's handler only sets a flag that its
  301. main loop polls, and a loop blocked in write() never reaches the check,
  302. so the whole grace period is dead time.
  303. * SIGKILL does kill it, but wait() cannot observe that. asyncio resolves
  304. Process.wait()'s waiter through BaseSubprocessTransport._try_finish(),
  305. which requires every pipe transport to report disconnected; paused,
  306. unread pipes never reach EOF, so wait() blocks with returncode already
  307. set. That is what made the "did not exit within Ns of SIGKILL" error
  308. fire on every single camera close, and unbounded it was the 12-hour
  309. hang in #2580.
  310. Draining fixes both: SIGTERM becomes actionable and the exit observable.
  311. Measured on an H2D: 4.0s of dead time per close before, ~0.15s after —
  312. which matters because the printer allows exactly one camera connection,
  313. so every one of those seconds was a connection nobody could use.
  314. Discarding what we drain is deliberate. The stream loop already reads
  315. stderr on its error paths (_read_ffmpeg_stderr), and it does so before
  316. calling this, so nothing diagnostic is lost.
  317. """
  318. if process.returncode is not None:
  319. _spawned_ffmpeg_pids.pop(process.pid, None)
  320. return # Already dead
  321. drainers = [asyncio.create_task(_drain_pipe(process.stdout))]
  322. # A streaming ffmpeg's stderr already has a reader (_FfmpegStderrTail), and
  323. # it keeps draining right through teardown, which is all we need here. Adding
  324. # a second reader would race it — asyncio rejects concurrent reads on one
  325. # StreamReader — so only drain stderr when nobody else owns it.
  326. if process.pid not in _stderr_tails:
  327. drainers.append(asyncio.create_task(_drain_pipe(process.stderr)))
  328. try:
  329. process.terminate()
  330. try:
  331. await asyncio.wait_for(process.wait(), timeout=_FFMPEG_TERM_TIMEOUT)
  332. except TimeoutError:
  333. logger.warning("ffmpeg didn't terminate gracefully, killing (stream_id=%s)", stream_id)
  334. process.kill()
  335. try:
  336. await asyncio.wait_for(process.wait(), timeout=_FFMPEG_KILL_TIMEOUT)
  337. except TimeoutError:
  338. # Do NOT keep waiting (#2580): the caller is the stream
  339. # generator, and blocking here pins the fan-out pump forever.
  340. # The orphan janitor reaps the process later. With the pipes
  341. # drained this should be unreachable — see _FFMPEG_KILL_TIMEOUT.
  342. logger.error(
  343. "ffmpeg did not exit within %.1fs of SIGKILL; abandoning wait (stream_id=%s)",
  344. _FFMPEG_KILL_TIMEOUT,
  345. stream_id,
  346. )
  347. except ProcessLookupError:
  348. pass # Already dead
  349. except OSError as e:
  350. logger.warning("Error terminating ffmpeg: %s", e)
  351. finally:
  352. for drainer in drainers:
  353. drainer.cancel()
  354. await asyncio.gather(*drainers, return_exceptions=True)
  355. _spawned_ffmpeg_pids.pop(process.pid, None)
  356. # The banner-stripping summariser moved to backend.app.utils.ffmpeg_output so
  357. # the seven other places that log ffmpeg stderr could stop truncating it from
  358. # the front (#2968). Imported under the private name this module has always
  359. # used: _FfmpegStderrTail and the tests both reach for it by that name.
  360. _summarize_ffmpeg_stderr = summarize_ffmpeg_stderr
  361. class _FfmpegStderrTail:
  362. """Owns a long-lived ffmpeg's stderr: drains it continuously, keeps the tail.
  363. Reading stderr only when something has already gone wrong leaves a pipe
  364. nobody reads for the whole life of the stream. ffmpeg writes its banner, the
  365. input analysis and then a progress line at a steady rate, so a 64 KiB pipe
  366. fills eventually and ffmpeg blocks writing to it — at which point it stops
  367. producing frames, the stream's own read timeout fires, and the log says
  368. "RTSP read timeout" with no hint that we starved it ourselves.
  369. How long that takes is unmeasured and may be a long time: one H2D upstream
  370. ran 21m36s continuously without stalling, so this is a bounded resource
  371. being treated as unbounded rather than an observed failure. Draining removes
  372. the ceiling either way, and the tail is *better* diagnostic material than
  373. the old on-demand read: it holds ffmpeg's most recent output at the moment
  374. things went wrong, where reading the buffered pipe returned whatever was
  375. printed first (usually the startup banner, which the summariser then strips).
  376. Registers itself in ``_stderr_tails`` so the two other readers of this pipe
  377. can defer to it — asyncio raises if two coroutines read one StreamReader
  378. concurrently. See ``_read_ffmpeg_stderr`` and ``_terminate_ffmpeg``.
  379. """
  380. def __init__(self, process: asyncio.subprocess.Process) -> None:
  381. self._process = process
  382. self._buffer = bytearray()
  383. self._task: asyncio.Task | None = None
  384. if process.stderr is None:
  385. return
  386. self._task = asyncio.create_task(self._pump())
  387. _stderr_tails[process.pid] = self
  388. async def _pump(self) -> None:
  389. reader = self._process.stderr
  390. try:
  391. while True:
  392. chunk = await reader.read(8192)
  393. if not chunk:
  394. return # EOF — ffmpeg has exited
  395. self._buffer.extend(chunk)
  396. excess = len(self._buffer) - _FFMPEG_STDERR_TAIL_BYTES
  397. if excess > 0:
  398. del self._buffer[:excess]
  399. except asyncio.CancelledError:
  400. raise
  401. except Exception: # noqa: BLE001 — a broken pipe just ends the tail
  402. return
  403. def text(self) -> str | None:
  404. """The retained tail, summarised. None when nothing was captured.
  405. Goes through _summarize_ffmpeg_stderr like every other stderr log in
  406. this module: ffmpeg echoes its input URL, which carries the access code.
  407. """
  408. if not self._buffer:
  409. return None
  410. return _summarize_ffmpeg_stderr(self._buffer.decode(errors="replace")) or None
  411. async def aclose(self) -> None:
  412. """Stop draining and release ownership of the pipe. Idempotent.
  413. Awaits the cancelled pump rather than firing and forgetting, so the task
  414. is finished before the caller moves on — an abandoned pending task
  415. becomes an "unraisable exception" warning at an arbitrary later point,
  416. usually during interpreter or loop teardown.
  417. """
  418. task, self._task = self._task, None
  419. if _stderr_tails.get(self._process.pid) is self:
  420. del _stderr_tails[self._process.pid]
  421. if task is None:
  422. return
  423. task.cancel()
  424. with contextlib.suppress(asyncio.CancelledError):
  425. await task
  426. async def _read_ffmpeg_stderr(process: asyncio.subprocess.Process) -> str | None:
  427. """Read whatever ffmpeg has written to stderr so far (best-effort).
  428. ffmpeg's stderr must be drained *incrementally*. A stalled-but-still-alive
  429. ffmpeg — the typical P2S RTSP failure, where it connects but never produces
  430. a frame — never closes stderr, so a plain ``stderr.read()`` (read-to-EOF)
  431. blocks until the wait_for timeout and returns nothing, discarding the
  432. banner + stream-analysis lines ffmpeg already printed. Reading in bounded
  433. chunks returns the buffered output promptly whether or not ffmpeg has
  434. exited. Returns the content with ffmpeg's boilerplate banner stripped.
  435. When a _FfmpegStderrTail owns this process's stderr — every streaming
  436. ffmpeg — its retained tail is returned instead. Reading the pipe here as
  437. well would race that collector, and asyncio refuses two concurrent readers
  438. on one StreamReader outright.
  439. """
  440. if not process:
  441. return None
  442. tail = _stderr_tails.get(getattr(process, "pid", None))
  443. if tail is not None:
  444. return tail.text()
  445. if not process.stderr:
  446. return None
  447. chunks: list[bytes] = []
  448. total = 0
  449. cap = 65536
  450. try:
  451. while total < cap:
  452. chunk = await asyncio.wait_for(process.stderr.read(8192), timeout=2.0)
  453. if not chunk:
  454. break # EOF — ffmpeg has exited
  455. chunks.append(chunk)
  456. total += len(chunk)
  457. except Exception:
  458. # Timed out waiting for more data — ffmpeg is alive but quiet now.
  459. # Fall through and return whatever it already printed.
  460. pass
  461. if not chunks:
  462. return None
  463. return _summarize_ffmpeg_stderr(b"".join(chunks).decode(errors="replace")) or None
  464. async def generate_rtsp_mjpeg_stream(
  465. ip_address: str,
  466. access_code: str,
  467. model: str | None,
  468. fps: int = 10,
  469. stream_id: str | None = None,
  470. disconnect_event: asyncio.Event | None = None,
  471. printer_id: int | None = None,
  472. ) -> AsyncGenerator[bytes, None]:
  473. """Generate MJPEG stream from printer camera using ffmpeg/RTSP.
  474. This is for X1/H2/P2 models that support RTSP streaming.
  475. Auto-reconnects when the printer drops the RTSP session (common on P2S).
  476. Per-model knobs (probesize, analyzeduration, reconnect cadence) come from
  477. :func:`camera_profiles.get_camera_profile` so quirky firmwares can be
  478. handled by adding a profile entry rather than tuning a global constant.
  479. """
  480. ffmpeg = get_ffmpeg_path()
  481. if not ffmpeg:
  482. logger.error("ffmpeg not found - camera streaming requires ffmpeg")
  483. yield (b"--frame\r\nContent-Type: text/plain\r\n\r\nError: ffmpeg not installed\r\n")
  484. return
  485. profile = get_camera_profile(model)
  486. port = get_camera_port(model)
  487. # Use a local TLS proxy so Python's OpenSSL handles TLS instead of
  488. # ffmpeg's GnuTLS. This fixes P2S (and potentially other models)
  489. # dropping the RTSP session after a few seconds due to GnuTLS's
  490. # hardened Debian defaults rejecting TLS renegotiation.
  491. proxy_port, proxy_server = await create_tls_proxy(ip_address, port)
  492. camera_url = f"rtsp://bblp:{access_code}@127.0.0.1:{proxy_port}/streaming/live/1"
  493. # ffmpeg command to output MJPEG stream to stdout
  494. cmd = [
  495. ffmpeg,
  496. "-rtsp_transport",
  497. "tcp",
  498. "-rtsp_flags",
  499. "prefer_tcp",
  500. # Socket I/O timeout name varies by ffmpeg version (#1504); see
  501. # rtsp_socket_timeout_flag(). The 30s value is microseconds for
  502. # both names.
  503. f"-{rtsp_socket_timeout_flag()}",
  504. "30000000",
  505. "-buffer_size",
  506. "1024000", # 1MB buffer
  507. "-max_delay",
  508. "500000", # 0.5 seconds max delay
  509. "-probesize",
  510. str(profile.probesize),
  511. "-analyzeduration",
  512. str(profile.analyzeduration),
  513. "-fflags",
  514. "nobuffer", # Reduce internal buffering
  515. "-flags",
  516. "low_delay", # Minimize decode latency
  517. *profile.extra_ffmpeg_input_args,
  518. "-i",
  519. camera_url,
  520. "-f",
  521. "mjpeg",
  522. "-q:v",
  523. "5",
  524. "-r",
  525. str(fps),
  526. "-an", # No audio
  527. "-", # Output to stdout
  528. ]
  529. # Register disconnect event so stop endpoint can signal us
  530. if stream_id and disconnect_event:
  531. _disconnect_events[stream_id] = disconnect_event
  532. logger.info(
  533. "Starting RTSP camera stream for %s (stream_id=%s, model=%s, fps=%s, probesize=%s, analyzeduration=%s)",
  534. ip_address,
  535. stream_id,
  536. model,
  537. fps,
  538. profile.probesize,
  539. profile.analyzeduration,
  540. )
  541. # Log the full argv so a support bundle shows the actual ffmpeg flags
  542. # (probesize, analyzeduration, transport, ...). Only camera_url carries a
  543. # secret (the access code), so redact just that one element.
  544. _redacted_cmd = ["rtsp://<redacted>/streaming/live/1" if a == camera_url else a for a in cmd]
  545. logger.debug("ffmpeg command: %s", " ".join(_redacted_cmd))
  546. # On Windows, spawn ffmpeg in its own process group so that
  547. # terminate() doesn't broadcast CTRL_C_EVENT to uvicorn (#605).
  548. spawn_kwargs: dict = {}
  549. if sys.platform == "win32":
  550. spawn_kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP
  551. jpeg_start = b"\xff\xd8"
  552. jpeg_end = b"\xff\xd9"
  553. reconnect_count = 0
  554. process = None
  555. stderr_tail: _FfmpegStderrTail | None = None
  556. got_any_frames = False
  557. # Across sessions (#3218): the frame a session froze on, and whether the
  558. # next session showed the very same picture -- a still scene, not a
  559. # frozen ffmpeg.
  560. frozen_crc: int | None = None
  561. still_scene = False
  562. try:
  563. while reconnect_count <= profile.rtsp_reconnect_max:
  564. # Check for client disconnect before (re)connecting
  565. if disconnect_event and disconnect_event.is_set():
  566. break
  567. if reconnect_count > 0:
  568. logger.info(
  569. "RTSP reconnecting (%d/%d) for %s (stream_id=%s)",
  570. reconnect_count,
  571. profile.rtsp_reconnect_max,
  572. ip_address,
  573. stream_id,
  574. )
  575. # Fast after a session that delivered frames (reconnect_count
  576. # is 1 then), backing off while the printer keeps refusing.
  577. await asyncio.sleep(
  578. min(
  579. profile.rtsp_reconnect_delay * 2 ** (reconnect_count - 1),
  580. profile.rtsp_reconnect_backoff_max,
  581. )
  582. )
  583. if disconnect_event and disconnect_event.is_set():
  584. break
  585. # Spawn ffmpeg
  586. process = await asyncio.create_subprocess_exec(
  587. *cmd,
  588. stdout=asyncio.subprocess.PIPE,
  589. stderr=asyncio.subprocess.PIPE,
  590. **spawn_kwargs,
  591. )
  592. if stream_id:
  593. _active_streams[stream_id] = process
  594. import time as _time
  595. _spawned_ffmpeg_pids[process.pid] = _time.time()
  596. # Brief check for immediate startup failures
  597. await asyncio.sleep(0.1)
  598. if process.returncode is not None:
  599. stderr = await process.stderr.read()
  600. stderr_text = _summarize_ffmpeg_stderr(stderr.decode(errors="replace"))
  601. logger.error("ffmpeg failed immediately (attempt %d): %s", reconnect_count + 1, stderr_text)
  602. _spawned_ffmpeg_pids.pop(process.pid, None)
  603. if not got_any_frames and reconnect_count == 0:
  604. # First attempt failed immediately — camera is likely unreachable
  605. yield (
  606. b"--frame\r\n"
  607. b"Content-Type: text/plain\r\n\r\n"
  608. b"Error: Camera connection failed. Check printer is on and camera is enabled.\r\n"
  609. )
  610. return
  611. reconnect_count += 1
  612. continue
  613. # Take ownership of stderr for the life of this process. Started
  614. # only after the immediate-failure check above, which reads the pipe
  615. # directly (correct there: the process is already dead, so
  616. # read-to-EOF returns at once and cannot be raced by a collector).
  617. # Nothing is lost by starting late — the banner ffmpeg printed in the
  618. # meantime is still sitting in the pipe.
  619. stderr_tail = _FfmpegStderrTail(process)
  620. # Read JPEG frames from ffmpeg stdout
  621. buffer = b""
  622. stream_ended = False
  623. client_gone = False
  624. session_got_frames = False
  625. # A frame that differs from the one before, not any frame, is what
  626. # shows the picture is live: ffmpeg can repeat its last one
  627. # forever (#3218).
  628. last_frame_crc: int | None = None
  629. last_change = time.time()
  630. identical_frames = 0
  631. frozen = False
  632. while True:
  633. if disconnect_event and disconnect_event.is_set():
  634. client_gone = True
  635. break
  636. try:
  637. chunk = await asyncio.wait_for(process.stdout.read(8192), timeout=30.0)
  638. if not chunk:
  639. # ffmpeg exited — log stderr and break to reconnect
  640. stderr_text = await _read_ffmpeg_stderr(process)
  641. if stderr_text:
  642. logger.warning("ffmpeg stderr (stream_id=%s): %s", stream_id, stderr_text)
  643. logger.warning("RTSP stream ended for %s (stream_id=%s), will reconnect", ip_address, stream_id)
  644. stream_ended = True
  645. break
  646. buffer += chunk
  647. # Extract complete JPEG frames from buffer
  648. while True:
  649. start_idx = buffer.find(jpeg_start)
  650. if start_idx == -1:
  651. buffer = buffer[-2:] if len(buffer) > 2 else buffer
  652. break
  653. if start_idx > 0:
  654. buffer = buffer[start_idx:]
  655. end_idx = buffer.find(jpeg_end, 2)
  656. if end_idx == -1:
  657. break
  658. frame = buffer[: end_idx + 2]
  659. buffer = buffer[end_idx + 2 :]
  660. got_any_frames = True
  661. session_got_frames = True
  662. now = time.time()
  663. frame_crc = zlib.crc32(frame)
  664. if last_frame_crc is None:
  665. # First frame of this session. The same frame the
  666. # last session froze on means the camera really
  667. # shows that picture (see _RTSP_STILL_RECHECK_SECONDS).
  668. still_scene = frozen_crc is not None and frame_crc == frozen_crc
  669. if still_scene:
  670. logger.info(
  671. "RTSP picture unchanged after restart for %s (stream_id=%s): "
  672. "treating it as a still scene, re-checking every %.0fs",
  673. ip_address,
  674. stream_id,
  675. _RTSP_STILL_RECHECK_SECONDS,
  676. )
  677. last_frame_crc = frame_crc
  678. last_change = now
  679. elif frame_crc != last_frame_crc:
  680. last_frame_crc = frame_crc
  681. last_change = now
  682. identical_frames = 0
  683. # The picture moves: back to the normal check.
  684. still_scene = False
  685. frozen_crc = None
  686. else:
  687. identical_frames += 1
  688. if printer_id is not None:
  689. _last_frames[printer_id] = frame
  690. _last_frame_times[printer_id] = now
  691. if stream_id:
  692. _stream_last_frame_times[stream_id] = now
  693. yield (
  694. b"--frame\r\n"
  695. b"Content-Type: image/jpeg\r\n"
  696. b"Content-Length: " + str(len(frame)).encode() + b"\r\n"
  697. b"\r\n" + frame + b"\r\n"
  698. )
  699. if now - last_change > (_RTSP_STILL_RECHECK_SECONDS if still_scene else _RTSP_FROZEN_SECONDS):
  700. frozen = True
  701. frozen_crc = last_frame_crc
  702. break
  703. if frozen:
  704. if still_scene:
  705. logger.info(
  706. "RTSP still-scene re-check for %s (stream_id=%s), restarting ffmpeg",
  707. ip_address,
  708. stream_id,
  709. )
  710. else:
  711. stderr_text = await _read_ffmpeg_stderr(process)
  712. if stderr_text:
  713. logger.warning("ffmpeg stderr (stream_id=%s): %s", stream_id, stderr_text)
  714. logger.warning(
  715. "RTSP output frozen for %s (stream_id=%s): %d identical frames over %.0fs, "
  716. "restarting ffmpeg",
  717. ip_address,
  718. stream_id,
  719. identical_frames,
  720. time.time() - last_change,
  721. )
  722. stream_ended = True
  723. break
  724. except TimeoutError:
  725. stderr_text = await _read_ffmpeg_stderr(process)
  726. if stderr_text:
  727. logger.warning("ffmpeg stderr on timeout: %s", stderr_text)
  728. logger.warning("RTSP read timeout for %s (stream_id=%s)", ip_address, stream_id)
  729. stream_ended = True
  730. break
  731. except asyncio.CancelledError:
  732. logger.info("Camera stream cancelled (stream_id=%s)", stream_id)
  733. client_gone = True
  734. break
  735. except GeneratorExit:
  736. logger.info("Camera stream generator exit (stream_id=%s)", stream_id)
  737. client_gone = True
  738. break
  739. # Clean up this ffmpeg process before reconnecting or exiting
  740. await _terminate_ffmpeg(process, stream_id)
  741. # Released after teardown, not before: _terminate_ffmpeg deliberately
  742. # leaves stderr to this collector, which has to keep draining while
  743. # the process is stopped or wait() can't observe the exit.
  744. if stderr_tail is not None:
  745. await stderr_tail.aclose()
  746. stderr_tail = None
  747. process = None
  748. if client_gone:
  749. break
  750. # Check if stream was explicitly stopped (e.g., by stop endpoint)
  751. if stream_id and stream_id not in _active_streams:
  752. logger.info("Stream %s removed from active streams, stopping reconnect", stream_id)
  753. break
  754. if stream_ended:
  755. # The budget is for failures in a row. A session that
  756. # delivered video was a success, however it ended -- a stock
  757. # X1C ends every session after about a minute, which under a
  758. # lifetime count stopped the live view for good after half an
  759. # hour.
  760. if session_got_frames:
  761. reconnect_count = 0
  762. reconnect_count += 1
  763. continue
  764. # Normal exit (shouldn't reach here, but be safe)
  765. break
  766. if reconnect_count > profile.rtsp_reconnect_max:
  767. logger.error(
  768. "RTSP max consecutive reconnects (%d) reached for %s (stream_id=%s)",
  769. profile.rtsp_reconnect_max,
  770. ip_address,
  771. stream_id,
  772. )
  773. except FileNotFoundError:
  774. logger.error("ffmpeg not found - camera streaming requires ffmpeg")
  775. yield (b"--frame\r\nContent-Type: text/plain\r\n\r\nError: ffmpeg not installed\r\n")
  776. except asyncio.CancelledError:
  777. logger.info("Camera stream task cancelled (stream_id=%s)", stream_id)
  778. except GeneratorExit:
  779. logger.info("Camera stream generator closed (stream_id=%s)", stream_id)
  780. except Exception as e:
  781. logger.exception("Camera stream error: %s", e)
  782. finally:
  783. # Remove from active streams and disconnect events
  784. if stream_id:
  785. _active_streams.pop(stream_id, None)
  786. _disconnect_events.pop(stream_id, None)
  787. _stream_last_frame_times.pop(stream_id, None)
  788. # Clean up frame buffer and timestamps
  789. _release_printer_frame_state(printer_id)
  790. if process:
  791. await _terminate_ffmpeg(process, stream_id)
  792. logger.info("Camera stream stopped for %s (stream_id=%s)", ip_address, stream_id)
  793. # Same order as in the loop: terminate first, then release stderr.
  794. if stderr_tail is not None:
  795. await stderr_tail.aclose()
  796. # Shut down the TLS proxy
  797. await close_tls_proxy(proxy_server)
  798. @router.post("/camera/stream-token")
  799. async def create_stream_token(
  800. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  801. ):
  802. """Create a reusable token for camera stream/snapshot access.
  803. Returns a token valid for 60 minutes that can be appended as ?token=xxx
  804. to camera stream/snapshot URLs loaded via <img> tags.
  805. """
  806. return {"token": await create_camera_stream_token()}
  807. @router.get("/{printer_id}/camera/stream")
  808. async def camera_stream(
  809. printer_id: int,
  810. request: Request,
  811. fps: int = 10,
  812. _: None = RequireCameraStreamTokenIfAuthEnabled,
  813. ):
  814. """Stream live video from printer camera as MJPEG.
  815. This endpoint returns a multipart MJPEG stream that can be used directly
  816. in an <img> tag or video player.
  817. Requires a stream token query param (?token=xxx) when auth is enabled.
  818. Uses external camera if configured, otherwise uses built-in camera:
  819. - External: MJPEG, RTSP, or HTTP snapshot
  820. - A1/P1: Chamber image protocol (port 6000)
  821. - X1/H2/P2: RTSP via ffmpeg (port 322)
  822. Args:
  823. printer_id: Printer ID
  824. fps: Target frames per second (default: 10, max: 30)
  825. """
  826. # Fetch the printer in a short-lived session so the pooled DB connection is
  827. # released BEFORE we start streaming. A live MJPEG stream runs for as long
  828. # as the browser tab stays open (potentially hours); holding the
  829. # Depends(get_db) session across it pinned one pooled connection per open
  830. # camera tab per printer — a top contributor to pool exhaustion on large
  831. # farms (issue #2572). expire_on_commit=False keeps the printer's already-
  832. # loaded columns readable after the session closes, and everything below
  833. # reads only scalar attributes (model, ip_address, access_code,
  834. # external_camera_*) — no lazy loads.
  835. #
  836. # Reference async_session via the module (not a top-level import binding) so
  837. # the session maker is looked up at call time — that keeps it in sync with
  838. # reinitialize_database() and lets the test harness's patch of
  839. # backend.app.core.database.async_session take effect here.
  840. async with database.async_session() as db:
  841. printer = await get_printer_or_404(printer_id, db)
  842. # Check for external camera first
  843. if printer.external_camera_enabled and printer.external_camera_url:
  844. # NB: no `import time` / `import uuid` here, and don't reintroduce them.
  845. # A local import anywhere in this function makes the name function-local
  846. # for the WHOLE function, so the RTSP/chamber path below — which never
  847. # executes this branch — would raise UnboundLocalError on any printer
  848. # without an external camera. Both are imported at module level.
  849. from backend.app.services.external_camera import generate_mjpeg_stream
  850. # Limit external camera FPS to reduce browser load
  851. fps = min(max(fps, 1), 15)
  852. logger.info(
  853. "Using external camera (%s) for printer %s at %s fps", printer.external_camera_type, printer_id, fps
  854. )
  855. # Register the stream into the SAME registries the RTSP/chamber paths use
  856. # (#2675) so `/camera/stop` and cleanup_orphaned_streams can find and kill
  857. # a leaked ffmpeg holding a USB device open. Before this, external streams
  858. # only tracked _active_external_streams and were structurally invisible to
  859. # both the stop endpoint and the janitor. The stream_id keeps the
  860. # `{printer_id}-` prefix both scanners key on, plus a unique suffix so two
  861. # concurrent viewers of one printer don't clobber each other's entry.
  862. stream_id = f"{printer_id}-ext-{uuid.uuid4().hex[:8]}"
  863. stop_event = asyncio.Event()
  864. _disconnect_events[stream_id] = stop_event
  865. # Track stream start
  866. _stream_start_times[printer_id] = time.time()
  867. _active_external_streams.add(printer_id)
  868. # Mutable holder so the wrapper's finally can unregister whatever process
  869. # is currently registered (the RTSP path may respawn across reconnects).
  870. current_proc: dict[str, asyncio.subprocess.Process] = {}
  871. def _register_external_process(proc: asyncio.subprocess.Process) -> None:
  872. prev = current_proc.get("proc")
  873. if prev is not None and prev.pid != proc.pid:
  874. _spawned_ffmpeg_pids.pop(prev.pid, None)
  875. current_proc["proc"] = proc
  876. _active_streams[stream_id] = proc
  877. _spawned_ffmpeg_pids[proc.pid] = time.time()
  878. _stream_last_frame_times[stream_id] = time.time()
  879. def _publish_external_frame(frame: bytes) -> None:
  880. """Make the live frame reusable by one-shot consumers (#2707).
  881. Only the built-in camera paths populated _last_frames, so every
  882. external-camera consumer — layer timelapse, finish photo, Obico,
  883. plate check — found an empty buffer and opened its own handle on a
  884. device that allows exactly one reader, which simply failed while a
  885. viewer was attached. Raw frame, not the multipart-wrapped chunk the
  886. generator yields, because that is what those consumers expect.
  887. """
  888. _last_frames[printer_id] = frame
  889. async def external_stream_wrapper():
  890. """Wrap external stream to track start/stop and update frame times."""
  891. try:
  892. async for frame in generate_mjpeg_stream(
  893. printer.external_camera_url,
  894. printer.external_camera_type,
  895. fps,
  896. on_process=_register_external_process,
  897. on_frame=_publish_external_frame,
  898. stop_event=stop_event,
  899. ):
  900. # generate_mjpeg_stream already handles rate limiting;
  901. # track frame times (per-printer + per-stream) for stall detection
  902. now = time.time()
  903. _last_frame_times[printer_id] = now
  904. _stream_last_frame_times[stream_id] = now
  905. yield frame
  906. finally:
  907. # Best-effort unregister. If an abrupt disconnect skips this
  908. # finally, the registry entries persist — which is exactly what
  909. # lets the stop endpoint / janitor reap the leaked process.
  910. stop_event.set()
  911. proc = current_proc.get("proc")
  912. if proc is not None:
  913. _spawned_ffmpeg_pids.pop(proc.pid, None)
  914. _active_streams.pop(stream_id, None)
  915. _disconnect_events.pop(stream_id, None)
  916. _stream_last_frame_times.pop(stream_id, None)
  917. _active_external_streams.discard(printer_id)
  918. # Now that this path publishes a buffered frame, it has to
  919. # retract it too — ownership-checked, so a concurrent viewer of
  920. # the same printer keeps its own. Also clears the per-printer
  921. # timings this path used to leave behind.
  922. _release_printer_frame_state(printer_id)
  923. logger.info("External camera stream ended for printer %s", printer_id)
  924. return StreamingResponse(
  925. external_stream_wrapper(),
  926. media_type="multipart/x-mixed-replace; boundary=frame",
  927. headers={
  928. "Cache-Control": "no-cache, no-store, must-revalidate",
  929. "Pragma": "no-cache",
  930. "Expires": "0",
  931. },
  932. )
  933. # Validate FPS - A1/P1 models max out at ~5 FPS
  934. if is_chamber_image_model(printer.model):
  935. fps = min(max(fps, 1), 5)
  936. else:
  937. fps = min(max(fps, 1), 30)
  938. # Choose the appropriate stream generator based on model
  939. if is_chamber_image_model(printer.model):
  940. stream_generator = generate_chamber_mjpeg_stream
  941. logger.info("Using chamber image protocol for %s", printer.model)
  942. else:
  943. stream_generator = generate_rtsp_mjpeg_stream
  944. logger.info("Using RTSP protocol for %s", printer.model)
  945. # Track stream start time. Set only if absent so the value reflects when
  946. # the SHARED upstream first started streaming, not when each new viewer
  947. # attached — otherwise /camera/status would report stream_uptime jumping
  948. # backward whenever a second viewer joins. The upstream generator's
  949. # finally clears this entry when the upstream actually ends.
  950. _stream_start_times.setdefault(printer_id, time.time())
  951. # Fan-out broadcaster (#1089): one upstream connection per printer, shared
  952. # across all viewers. Most Bambu printers only allow a single concurrent
  953. # camera connection, so opening the same printer in two tabs would
  954. # otherwise kick the first viewer off. The broadcaster owns the single
  955. # upstream and the per-viewer disconnect handling.
  956. #
  957. # Note: the upstream's fps is fixed by the first viewer who creates the
  958. # broadcaster. Concurrent viewers share that rate; new viewers after
  959. # teardown create a fresh broadcaster at their requested fps.
  960. fanout_key = f"printer-{printer_id}"
  961. upstream_stream_id = _new_fanout_stream_id(printer_id)
  962. def _factory(disconnect_event: asyncio.Event):
  963. # Re-bind locals into the closure so the async generator below sees
  964. # them — disconnect_event is owned by the broadcaster and signalled
  965. # when the last subscriber leaves (after the grace window).
  966. return stream_generator(
  967. ip_address=printer.ip_address,
  968. access_code=printer.access_code,
  969. model=printer.model,
  970. fps=fps,
  971. stream_id=upstream_stream_id,
  972. disconnect_event=disconnect_event,
  973. printer_id=printer_id,
  974. )
  975. # Subscribe with a one-shot retry to close a tiny race: the grace-window
  976. # teardown can flip the broadcaster to `stopped=True` between the registry
  977. # lookup and our subscribe call. The retry forces the registry to mint a
  978. # fresh broadcaster (since the now-stopped one is replaced), and the second
  979. # subscribe is guaranteed to land on it before any teardown can fire.
  980. broadcaster: MjpegBroadcaster = await get_or_create_broadcaster(fanout_key, _factory)
  981. try:
  982. queue = await broadcaster.subscribe()
  983. except RuntimeError:
  984. broadcaster = await get_or_create_broadcaster(fanout_key, _factory)
  985. queue = await broadcaster.subscribe()
  986. logger.info(
  987. "Camera viewer attached to %s (subscribers=%d)",
  988. fanout_key,
  989. broadcaster.subscriber_count,
  990. )
  991. async def _is_disconnected() -> bool:
  992. try:
  993. return await request.is_disconnected()
  994. except Exception:
  995. # Older starlette/uvicorn can raise during teardown — treat that
  996. # as "client gone" so the subscriber cleanly unsubscribes.
  997. return True
  998. def _log_detach(remaining: int) -> None:
  999. logger.info("Camera viewer detached from %s (subscribers=%d)", fanout_key, remaining)
  1000. async def _generate():
  1001. async for chunk in iter_subscriber(
  1002. broadcaster,
  1003. queue,
  1004. is_disconnected=_is_disconnected,
  1005. on_unsubscribe=_log_detach,
  1006. ):
  1007. yield chunk
  1008. return StreamingResponse(
  1009. _generate(),
  1010. media_type="multipart/x-mixed-replace; boundary=frame",
  1011. headers={
  1012. "Cache-Control": "no-cache, no-store, must-revalidate",
  1013. "Pragma": "no-cache",
  1014. "Expires": "0",
  1015. },
  1016. )
  1017. @router.api_route("/{printer_id}/camera/stop", methods=["GET", "POST"])
  1018. async def stop_camera_stream(
  1019. printer_id: int,
  1020. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  1021. ):
  1022. """Stop active camera streams for a printer.
  1023. Called by the frontend on viewer unmount (cam-wall tile, embedded viewer,
  1024. popup window). Accepts both GET and POST (POST for sendBeacon compatibility).
  1025. Reference-count guard: every viewer of a printer subscribes to the same
  1026. fan-out broadcaster, so a force-shutdown triggered by ONE leaving viewer
  1027. used to kill the others' streams (cam-wall tile froze when a user opened
  1028. then closed the embedded viewer). If any subscriber is still attached,
  1029. skip the force-teardown — the broadcaster's natural grace-shutdown (5 s
  1030. after subscribers drop to 0) handles cleanup when the leaving viewer's
  1031. HTTP connection actually closes.
  1032. """
  1033. broadcaster_key = f"printer-{printer_id}"
  1034. remaining_subscribers = get_subscriber_count(broadcaster_key)
  1035. if remaining_subscribers >= 1:
  1036. logger.info(
  1037. "Skipping force-shutdown for printer %s: %d subscriber(s) still attached; "
  1038. "natural cleanup will tear down when last viewer disconnects",
  1039. printer_id,
  1040. remaining_subscribers,
  1041. )
  1042. return {"stopped": 0, "skipped": True}
  1043. stopped = 0
  1044. # Tear down the fan-out broadcaster first (#1089). This cleanly notifies
  1045. # all subscribed viewers and asks the upstream generator to stop
  1046. # reconnecting before we fall back to forcefully killing the process below.
  1047. if await shutdown_broadcaster(broadcaster_key):
  1048. logger.info("Shut down camera fan-out broadcaster for printer %s", printer_id)
  1049. # Stop ffmpeg/RTSP streams
  1050. to_remove = []
  1051. for stream_id, process in list(_active_streams.items()):
  1052. if stream_id.startswith(f"{printer_id}-"):
  1053. to_remove.append(stream_id)
  1054. # Signal the generator to stop reconnecting BEFORE killing the process
  1055. event = _disconnect_events.get(stream_id)
  1056. if event:
  1057. event.set()
  1058. if process.returncode is None:
  1059. # Shared helper, not an inline copy: it bounds the post-kill
  1060. # wait (#2580) — a killed-but-unreaped ffmpeg used to hang this
  1061. # request forever, exactly when the user hit Stop to recover a
  1062. # stuck stream.
  1063. await _terminate_ffmpeg(process, stream_id)
  1064. stopped += 1
  1065. logger.info("Terminated ffmpeg process for stream %s", stream_id)
  1066. _spawned_ffmpeg_pids.pop(process.pid, None)
  1067. for stream_id in to_remove:
  1068. _active_streams.pop(stream_id, None)
  1069. _disconnect_events.pop(stream_id, None)
  1070. _stream_last_frame_times.pop(stream_id, None)
  1071. # Stop chamber image streams
  1072. to_remove_chamber = []
  1073. for stream_id, (_reader, writer) in list(_active_chamber_streams.items()):
  1074. if stream_id.startswith(f"{printer_id}-"):
  1075. to_remove_chamber.append(stream_id)
  1076. # Signal the generator to stop
  1077. event = _disconnect_events.get(stream_id)
  1078. if event:
  1079. event.set()
  1080. try:
  1081. writer.close()
  1082. stopped += 1
  1083. logger.info("Closed chamber image connection for stream %s", stream_id)
  1084. except OSError as e:
  1085. logger.warning("Error stopping chamber stream %s: %s", stream_id, e)
  1086. for stream_id in to_remove_chamber:
  1087. _active_chamber_streams.pop(stream_id, None)
  1088. _disconnect_events.pop(stream_id, None)
  1089. _stream_last_frame_times.pop(stream_id, None)
  1090. logger.info("Stopped %s camera stream(s) for printer %s", stopped, printer_id)
  1091. return {"stopped": stopped}
  1092. @router.get("/{printer_id}/camera/snapshot")
  1093. async def camera_snapshot(
  1094. printer_id: int,
  1095. _: None = RequireCameraStreamTokenIfAuthEnabled,
  1096. ):
  1097. """Capture a single frame from the printer camera.
  1098. Returns a JPEG image.
  1099. Requires a stream token query param (?token=xxx) when auth is enabled.
  1100. """
  1101. import tempfile
  1102. from pathlib import Path
  1103. # Fetch the printer in a short-lived session and release the pooled DB
  1104. # connection BEFORE the camera capture below (up to 15s, longer under a
  1105. # saturated FTP/camera pool). Holding a Depends(get_db) session across the
  1106. # grab pinned one connection per snapshot — and the cam wall polls this
  1107. # per tile every 8s — so overlapping captures could pile up connections on
  1108. # a large farm (issue #2572, sibling of the camera_stream fix). Everything
  1109. # below reads only already-loaded scalar columns (expire_on_commit=False).
  1110. async with database.async_session() as db:
  1111. printer = await get_printer_or_404(printer_id, db)
  1112. # Check for external camera first
  1113. if printer.external_camera_enabled and printer.external_camera_url:
  1114. from backend.app.services.external_camera import capture_frame
  1115. frame_data = await capture_frame(
  1116. printer.external_camera_url,
  1117. printer.external_camera_type,
  1118. timeout=15,
  1119. snapshot_url=printer.external_camera_snapshot_url,
  1120. )
  1121. if not frame_data:
  1122. raise HTTPException(
  1123. status_code=503,
  1124. detail="Failed to capture frame from external camera.",
  1125. )
  1126. return Response(
  1127. content=frame_data,
  1128. media_type="image/jpeg",
  1129. headers={
  1130. "Cache-Control": "no-cache, no-store, must-revalidate",
  1131. "Content-Disposition": f'inline; filename="snapshot_{printer_id}.jpg"',
  1132. },
  1133. )
  1134. # Reuse the fan-out broadcaster's buffered frame when a viewer is already
  1135. # watching — avoids opening a second concurrent RTSP socket on printers
  1136. # that allow only one camera connection (e.g. X2D firmware 01.01.00.00;
  1137. # see #1271). Buffered frame is <1s old while a viewer is connected.
  1138. buffered = try_get_active_buffered_frame(printer_id)
  1139. if buffered:
  1140. return Response(
  1141. content=buffered,
  1142. media_type="image/jpeg",
  1143. headers={
  1144. "Cache-Control": "no-cache, no-store, must-revalidate",
  1145. "Content-Disposition": f'inline; filename="snapshot_{printer_id}.jpg"',
  1146. },
  1147. )
  1148. # Create temporary file for the snapshot (0600 so only the app user can read it)
  1149. fd, tmp_name = tempfile.mkstemp(suffix=".jpg")
  1150. os.close(fd)
  1151. temp_path = Path(tmp_name)
  1152. temp_path.chmod(0o600)
  1153. try:
  1154. success = await capture_camera_frame(
  1155. ip_address=printer.ip_address,
  1156. access_code=printer.access_code,
  1157. model=printer.model,
  1158. output_path=temp_path,
  1159. timeout=15,
  1160. )
  1161. if not success:
  1162. raise HTTPException(
  1163. status_code=503,
  1164. detail="Failed to capture camera frame. Ensure printer is on and camera is enabled.",
  1165. )
  1166. # Read and return the image
  1167. with open(temp_path, "rb") as f:
  1168. image_data = f.read()
  1169. return Response(
  1170. content=image_data,
  1171. media_type="image/jpeg",
  1172. headers={
  1173. "Cache-Control": "no-cache, no-store, must-revalidate",
  1174. "Content-Disposition": f'inline; filename="snapshot_{printer_id}.jpg"',
  1175. },
  1176. )
  1177. finally:
  1178. # Clean up temp file
  1179. if temp_path.exists():
  1180. temp_path.unlink()
  1181. @router.get("/{printer_id}/camera/test")
  1182. async def test_camera(
  1183. printer_id: int,
  1184. db: AsyncSession = Depends(get_db),
  1185. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  1186. ):
  1187. """Test camera connection for a printer.
  1188. Returns success status and any error message.
  1189. """
  1190. printer = await get_printer_or_404(printer_id, db)
  1191. result = await test_camera_connection(
  1192. ip_address=printer.ip_address,
  1193. access_code=printer.access_code,
  1194. model=printer.model,
  1195. )
  1196. return result
  1197. @router.post("/{printer_id}/camera/diagnose")
  1198. async def diagnose_camera_route(
  1199. printer_id: int,
  1200. db: AsyncSession = Depends(get_db),
  1201. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  1202. ):
  1203. """Run staged diagnostics for a printer's camera path.
  1204. Returns a structured result the frontend renders inline so users can
  1205. self-diagnose "connection lost" before opening a ticket. See
  1206. ``camera_diagnose`` for stage details and the live-stream shortcut.
  1207. """
  1208. import time
  1209. from backend.app.services.camera_diagnose import diagnose_camera
  1210. printer = await get_printer_or_404(printer_id, db)
  1211. # Look up live-stream evidence so the diagnostic can short-circuit
  1212. # instead of fighting a viewer for the printer's single camera slot.
  1213. has_live = is_stream_active(printer_id)
  1214. last_ts = _last_frame_times.get(printer_id) if has_live else None
  1215. live_age = (time.time() - last_ts) if (has_live and last_ts) else None
  1216. result = await diagnose_camera(
  1217. ip_address=printer.ip_address,
  1218. access_code=printer.access_code,
  1219. model=printer.model,
  1220. printer_id=printer_id,
  1221. has_live_stream=has_live,
  1222. live_frame_age_seconds=live_age,
  1223. )
  1224. return result.to_dict()
  1225. @router.get("/{printer_id}/camera/status")
  1226. async def camera_status(
  1227. printer_id: int,
  1228. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  1229. ):
  1230. """Get the status of an active camera stream.
  1231. Returns whether a stream is active and when the last frame was received.
  1232. Used by the frontend to detect stalled streams and auto-reconnect.
  1233. """
  1234. import time
  1235. # Check if there's an active stream for this printer
  1236. has_active_stream = False
  1237. # Check external camera streams
  1238. if printer_id in _active_external_streams:
  1239. has_active_stream = True
  1240. # Check ffmpeg/RTSP streams
  1241. if not has_active_stream:
  1242. for stream_id in _active_streams:
  1243. if stream_id.startswith(f"{printer_id}-"):
  1244. process = _active_streams[stream_id]
  1245. if process.returncode is None:
  1246. has_active_stream = True
  1247. break
  1248. # Check chamber image streams
  1249. if not has_active_stream:
  1250. for stream_id in _active_chamber_streams:
  1251. if stream_id.startswith(f"{printer_id}-"):
  1252. has_active_stream = True
  1253. break
  1254. # Get timing information
  1255. current_time = time.time()
  1256. last_frame_time = _last_frame_times.get(printer_id)
  1257. stream_start_time = _stream_start_times.get(printer_id)
  1258. # Calculate seconds since last frame
  1259. seconds_since_frame = None
  1260. if last_frame_time is not None:
  1261. seconds_since_frame = current_time - last_frame_time
  1262. # Calculate stream uptime
  1263. stream_uptime = None
  1264. if stream_start_time is not None:
  1265. stream_uptime = current_time - stream_start_time
  1266. return {
  1267. "active": has_active_stream,
  1268. "has_frames": printer_id in _last_frames,
  1269. "seconds_since_frame": seconds_since_frame,
  1270. "stream_uptime": stream_uptime,
  1271. # Consider stalled if no frame for more than 10 seconds after stream started
  1272. "stalled": (
  1273. has_active_stream
  1274. and stream_uptime is not None
  1275. and stream_uptime > 5 # Give 5 seconds for stream to start
  1276. and (seconds_since_frame is None or seconds_since_frame > 10)
  1277. ),
  1278. }
  1279. @router.post("/{printer_id}/camera/external/test")
  1280. async def test_external_camera(
  1281. printer_id: int,
  1282. url: str,
  1283. camera_type: str,
  1284. db: AsyncSession = Depends(get_db),
  1285. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  1286. ):
  1287. """Test external camera connection.
  1288. Args:
  1289. printer_id: Printer ID (for authorization)
  1290. url: Camera URL or USB device path to test
  1291. camera_type: Camera type ("mjpeg", "rtsp", "snapshot", "usb")
  1292. Returns:
  1293. Dict with {success: bool, error?: str, resolution?: str}
  1294. """
  1295. # Verify printer exists (for authorization)
  1296. await get_printer_or_404(printer_id, db)
  1297. from backend.app.services.external_camera import test_connection
  1298. return await test_connection(url, camera_type)
  1299. @router.get("/{printer_id}/camera/check-plate")
  1300. async def check_plate_empty(
  1301. printer_id: int,
  1302. plate_type: str | None = None,
  1303. use_external: bool | None = None,
  1304. include_debug_image: bool = False,
  1305. db: AsyncSession = Depends(get_db),
  1306. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  1307. ):
  1308. """Check if the build plate is empty using camera vision.
  1309. Uses calibration-based difference detection - compares current frame
  1310. to a reference image of the empty plate.
  1311. IMPORTANT: Chamber light must be ON for reliable detection.
  1312. Args:
  1313. printer_id: Printer ID
  1314. plate_type: Type of build plate (e.g., "High Temp Plate") for calibration lookup
  1315. use_external: If True, prefer external camera over built-in. When omitted
  1316. (None), defaults to the printer's external_camera_enabled setting —
  1317. mirroring the runtime auto-check at print start (main.py). Without
  1318. this default the UI's manual check would always use the built-in
  1319. camera, mismatching the reference saved during calibration (#1359).
  1320. include_debug_image: If True, return URL to annotated debug image
  1321. Returns:
  1322. Dict with detection results:
  1323. - is_empty: bool - Whether plate appears empty
  1324. - confidence: float - Confidence level (0.0 to 1.0)
  1325. - difference_percent: float - How different from calibration reference
  1326. - message: str - Human-readable result message
  1327. - needs_calibration: bool - True if calibration is required
  1328. - light_warning: bool - True if chamber light is off
  1329. """
  1330. from backend.app.services.plate_detection import (
  1331. check_plate_empty as do_check,
  1332. is_plate_detection_available,
  1333. )
  1334. from backend.app.services.printer_manager import printer_manager
  1335. # Check printer exists first (before OpenCV check)
  1336. printer = await get_printer_or_404(printer_id, db)
  1337. if use_external is None:
  1338. use_external = bool(
  1339. printer.external_camera_enabled and printer.external_camera_url and printer.external_camera_type
  1340. )
  1341. if not is_plate_detection_available():
  1342. raise HTTPException(
  1343. status_code=503,
  1344. detail="Plate detection not available. Install opencv-python-headless to enable.",
  1345. )
  1346. # Check chamber light status
  1347. light_warning = False
  1348. state = printer_manager.get_status(printer_id)
  1349. if state and not state.chamber_light:
  1350. light_warning = True
  1351. from backend.app.services.plate_detection import PlateDetector
  1352. # Build ROI tuple from printer settings if available
  1353. roi = None
  1354. if all(
  1355. [
  1356. printer.plate_detection_roi_x is not None,
  1357. printer.plate_detection_roi_y is not None,
  1358. printer.plate_detection_roi_w is not None,
  1359. printer.plate_detection_roi_h is not None,
  1360. ]
  1361. ):
  1362. roi = (
  1363. printer.plate_detection_roi_x,
  1364. printer.plate_detection_roi_y,
  1365. printer.plate_detection_roi_w,
  1366. printer.plate_detection_roi_h,
  1367. )
  1368. result = await do_check(
  1369. printer_id=printer.id,
  1370. ip_address=printer.ip_address,
  1371. access_code=printer.access_code,
  1372. model=printer.model,
  1373. plate_type=plate_type,
  1374. include_debug_image=include_debug_image,
  1375. external_camera_url=printer.external_camera_url if printer.external_camera_enabled else None,
  1376. external_camera_type=printer.external_camera_type if printer.external_camera_enabled else None,
  1377. use_external=use_external,
  1378. roi=roi,
  1379. external_camera_snapshot_url=printer.external_camera_snapshot_url if printer.external_camera_enabled else None,
  1380. )
  1381. # Get reference count for the response
  1382. detector = PlateDetector()
  1383. ref_count = detector.get_calibration_count(printer.id)
  1384. response = result.to_dict()
  1385. response["light_warning"] = light_warning
  1386. response["reference_count"] = ref_count
  1387. response["max_references"] = detector.MAX_REFERENCES
  1388. # Include current ROI in response
  1389. if roi:
  1390. response["roi"] = {"x": roi[0], "y": roi[1], "w": roi[2], "h": roi[3]}
  1391. else:
  1392. # Return default ROI
  1393. response["roi"] = {"x": 0.15, "y": 0.35, "w": 0.70, "h": 0.55}
  1394. # If debug image requested and available, encode as base64 data URL
  1395. if include_debug_image and result.debug_image:
  1396. import base64
  1397. b64_image = base64.b64encode(result.debug_image).decode("utf-8")
  1398. response["debug_image_url"] = f"data:image/jpeg;base64,{b64_image}"
  1399. return response
  1400. @router.post("/{printer_id}/camera/plate-detection/calibrate")
  1401. async def calibrate_plate_detection(
  1402. printer_id: int,
  1403. label: str | None = None,
  1404. use_external: bool | None = None,
  1405. db: AsyncSession = Depends(get_db),
  1406. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  1407. ):
  1408. """Calibrate plate detection by capturing a reference image of the empty plate.
  1409. The plate MUST be empty when calling this endpoint. The captured image
  1410. will be used as the reference for future detection comparisons.
  1411. Supports up to 5 reference images per printer. When adding a 6th, the oldest
  1412. is automatically removed.
  1413. IMPORTANT: Chamber light should be ON for calibration.
  1414. Args:
  1415. printer_id: Printer ID
  1416. label: Optional label for this reference (e.g., "High Temp Plate", "Wham Bam")
  1417. use_external: If True, prefer external camera over built-in. When omitted
  1418. (None), defaults to the printer's external_camera_enabled setting so
  1419. calibration captures from the same source the runtime auto-check
  1420. uses at print start (#1359).
  1421. Returns:
  1422. Dict with:
  1423. - success: bool - Whether calibration succeeded
  1424. - message: str - Status message
  1425. - index: int - The reference slot used (0-4)
  1426. """
  1427. from backend.app.services.plate_detection import (
  1428. calibrate_plate,
  1429. is_plate_detection_available,
  1430. )
  1431. from backend.app.services.printer_manager import printer_manager
  1432. # Check printer exists first (before OpenCV check)
  1433. printer = await get_printer_or_404(printer_id, db)
  1434. if use_external is None:
  1435. use_external = bool(
  1436. printer.external_camera_enabled and printer.external_camera_url and printer.external_camera_type
  1437. )
  1438. if not is_plate_detection_available():
  1439. raise HTTPException(
  1440. status_code=503,
  1441. detail="Plate detection not available. Install opencv-python-headless to enable.",
  1442. )
  1443. # Check chamber light - warn but don't block
  1444. state = printer_manager.get_status(printer_id)
  1445. light_warning = state and not state.chamber_light
  1446. success, message, index = await calibrate_plate(
  1447. printer_id=printer.id,
  1448. ip_address=printer.ip_address,
  1449. access_code=printer.access_code,
  1450. model=printer.model,
  1451. label=label,
  1452. external_camera_url=printer.external_camera_url if printer.external_camera_enabled else None,
  1453. external_camera_type=printer.external_camera_type if printer.external_camera_enabled else None,
  1454. use_external=use_external,
  1455. external_camera_snapshot_url=printer.external_camera_snapshot_url if printer.external_camera_enabled else None,
  1456. )
  1457. if light_warning and success:
  1458. message += " (Warning: Chamber light was off)"
  1459. return {"success": success, "message": message, "index": index}
  1460. @router.delete("/{printer_id}/camera/plate-detection/calibrate")
  1461. async def delete_plate_calibration(
  1462. printer_id: int,
  1463. plate_type: str | None = None,
  1464. db: AsyncSession = Depends(get_db),
  1465. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  1466. ):
  1467. """Delete the plate detection calibration for a printer and plate type.
  1468. Args:
  1469. printer_id: Printer ID
  1470. plate_type: Type of build plate (if None, deletes legacy non-plate-specific calibration)
  1471. Returns:
  1472. Dict with:
  1473. - success: bool - Whether deletion succeeded
  1474. - message: str - Status message
  1475. """
  1476. from backend.app.services.plate_detection import (
  1477. delete_calibration,
  1478. is_plate_detection_available,
  1479. )
  1480. # Verify printer exists first (before OpenCV check)
  1481. await get_printer_or_404(printer_id, db)
  1482. if not is_plate_detection_available():
  1483. raise HTTPException(
  1484. status_code=503,
  1485. detail="Plate detection not available. Install opencv-python-headless to enable.",
  1486. )
  1487. deleted = delete_calibration(printer_id, plate_type)
  1488. plate_msg = f" for '{plate_type}'" if plate_type else ""
  1489. return {
  1490. "success": deleted,
  1491. "message": f"Calibration deleted{plate_msg}" if deleted else f"No calibration found{plate_msg}",
  1492. }
  1493. @router.get("/{printer_id}/camera/plate-detection/status")
  1494. async def get_plate_detection_status(
  1495. printer_id: int,
  1496. plate_type: str | None = None,
  1497. db: AsyncSession = Depends(get_db),
  1498. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  1499. ):
  1500. """Check plate detection status for a printer and plate type.
  1501. Returns:
  1502. Dict with:
  1503. - available: bool - Whether OpenCV is installed
  1504. - calibrated: bool - Whether printer has calibration for this plate type
  1505. - plate_type: str - The plate type queried
  1506. - chamber_light: bool - Whether chamber light is on
  1507. - message: str - Status message
  1508. """
  1509. from backend.app.services.plate_detection import (
  1510. get_calibration_status,
  1511. is_plate_detection_available,
  1512. )
  1513. from backend.app.services.printer_manager import printer_manager
  1514. # Verify printer exists first (before OpenCV check)
  1515. await get_printer_or_404(printer_id, db)
  1516. if not is_plate_detection_available():
  1517. return {
  1518. "available": False,
  1519. "calibrated": False,
  1520. "plate_type": plate_type,
  1521. "chamber_light": False,
  1522. "message": "OpenCV not installed",
  1523. }
  1524. # Get chamber light status
  1525. state = printer_manager.get_status(printer_id)
  1526. chamber_light = state.chamber_light if state else False
  1527. status = get_calibration_status(printer_id, plate_type)
  1528. status["chamber_light"] = chamber_light
  1529. return status
  1530. @router.get("/{printer_id}/camera/plate-detection/references")
  1531. async def get_plate_references(
  1532. printer_id: int,
  1533. db: AsyncSession = Depends(get_db),
  1534. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  1535. ):
  1536. """Get all calibration references for a printer with metadata.
  1537. Returns list of references with index, label, timestamp, and thumbnail URL.
  1538. """
  1539. from backend.app.services.plate_detection import PlateDetector, is_plate_detection_available
  1540. # Verify printer exists first (before OpenCV check)
  1541. await get_printer_or_404(printer_id, db)
  1542. if not is_plate_detection_available():
  1543. raise HTTPException(503, "Plate detection not available")
  1544. detector = PlateDetector()
  1545. references = detector.get_references(printer_id)
  1546. # Add thumbnail URLs
  1547. for ref in references:
  1548. ref["thumbnail_url"] = (
  1549. f"/api/v1/printers/{printer_id}/camera/plate-detection/references/{ref['index']}/thumbnail"
  1550. )
  1551. return {
  1552. "references": references,
  1553. "max_references": detector.MAX_REFERENCES,
  1554. }
  1555. @router.get("/{printer_id}/camera/plate-detection/references/{index}/thumbnail")
  1556. async def get_reference_thumbnail(
  1557. printer_id: int,
  1558. index: int,
  1559. db: AsyncSession = Depends(get_db),
  1560. _: None = RequireCameraStreamTokenIfAuthEnabled,
  1561. ):
  1562. """Get thumbnail image for a calibration reference.
  1563. Requires a stream token query param (?token=xxx) when auth is enabled.
  1564. """
  1565. from fastapi.responses import Response
  1566. from backend.app.services.plate_detection import PlateDetector, is_plate_detection_available
  1567. # Verify printer exists first (before OpenCV check)
  1568. await get_printer_or_404(printer_id, db)
  1569. if not is_plate_detection_available():
  1570. raise HTTPException(503, "Plate detection not available")
  1571. detector = PlateDetector()
  1572. thumbnail = detector.get_reference_thumbnail(printer_id, index)
  1573. if thumbnail is None:
  1574. raise HTTPException(404, "Reference not found")
  1575. return Response(content=thumbnail, media_type="image/jpeg")
  1576. @router.put("/{printer_id}/camera/plate-detection/references/{index}")
  1577. async def update_reference_label(
  1578. printer_id: int,
  1579. index: int,
  1580. label: str,
  1581. db: AsyncSession = Depends(get_db),
  1582. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  1583. ):
  1584. """Update the label for a calibration reference."""
  1585. from backend.app.services.plate_detection import PlateDetector, is_plate_detection_available
  1586. # Verify printer exists first (before OpenCV check)
  1587. await get_printer_or_404(printer_id, db)
  1588. if not is_plate_detection_available():
  1589. raise HTTPException(503, "Plate detection not available")
  1590. detector = PlateDetector()
  1591. success = detector.update_reference_label(printer_id, index, label)
  1592. if not success:
  1593. raise HTTPException(404, "Reference not found")
  1594. return {"success": True, "index": index, "label": label}
  1595. @router.delete("/{printer_id}/camera/plate-detection/references/{index}")
  1596. async def delete_reference(
  1597. printer_id: int,
  1598. index: int,
  1599. db: AsyncSession = Depends(get_db),
  1600. _: User | None = RequirePermissionIfAuthEnabled(Permission.CAMERA_VIEW),
  1601. ):
  1602. """Delete a specific calibration reference."""
  1603. from backend.app.services.plate_detection import PlateDetector, is_plate_detection_available
  1604. # Verify printer exists first (before OpenCV check)
  1605. await get_printer_or_404(printer_id, db)
  1606. if not is_plate_detection_available():
  1607. raise HTTPException(503, "Plate detection not available")
  1608. detector = PlateDetector()
  1609. success = detector.delete_reference(printer_id, index)
  1610. if not success:
  1611. raise HTTPException(404, "Reference not found")
  1612. return {"success": True, "message": "Reference deleted"}
  1613. def _scan_bambu_ffmpeg_pids() -> list[int]:
  1614. """Scan /proc for ffmpeg processes that are ours.
  1615. Two shapes are matched, both unambiguously Bambuddy's:
  1616. - Bambu RTSP: no other software connects to ``rtsp(s)://bblp:``.
  1617. - External USB (V4L2): an ffmpeg spawned with ``-f v4l2`` is our USB camera
  1618. stream (#2675). Only orphans are killed — the caller excludes PIDs still in
  1619. ``_active_streams``, so a live USB stream (now registered there) is spared.
  1620. This catches orphans that survive app restarts and are not in any tracking dict.
  1621. """
  1622. import os
  1623. pids = []
  1624. try:
  1625. for entry in os.listdir("/proc"):
  1626. if not entry.isdigit():
  1627. continue
  1628. try:
  1629. with open(f"/proc/{entry}/cmdline", "rb") as f:
  1630. cmdline = f.read()
  1631. if b"ffmpeg" not in cmdline:
  1632. continue
  1633. # Match both rtsp:// (via TLS proxy) and rtsps:// (direct), plus
  1634. # the `-f v4l2` input flag our USB camera command always carries.
  1635. if b"rtsp://bblp:" in cmdline or b"rtsps://bblp:" in cmdline or b"v4l2" in cmdline:
  1636. pids.append(int(entry))
  1637. except (OSError, PermissionError, ValueError):
  1638. continue
  1639. except OSError:
  1640. pass
  1641. return pids
  1642. async def cleanup_orphaned_streams():
  1643. """Clean up orphaned ffmpeg processes and stale stream entries.
  1644. Called periodically from the background task loop in main.py.
  1645. Three-layer cleanup:
  1646. 1. /proc scan — finds ALL Bambu ffmpeg processes on the system, even those
  1647. from previous app sessions. This is the nuclear safety net.
  1648. 2. _spawned_ffmpeg_pids — tracks PIDs spawned this session, catches orphans
  1649. that were removed from _active_streams but not killed.
  1650. 3. _active_streams — kills stale entries with no recent frames.
  1651. """
  1652. import os
  1653. import signal
  1654. import time
  1655. cleaned = 0
  1656. now = time.time()
  1657. # Collect PIDs that are legitimately in-use (active stream, process alive)
  1658. active_pids = {proc.pid for proc in _active_streams.values() if proc.returncode is None}
  1659. # Also exclude PIDs from one-shot snapshot captures (Obico detection, finish photos, etc.)
  1660. from backend.app.services.camera import _active_capture_pids
  1661. active_pids |= _active_capture_pids
  1662. # 1. /proc scan — catch ALL orphaned Bambu ffmpeg processes on the system.
  1663. # Any ffmpeg with rtsp(s)://bblp: that is NOT in an active stream is orphaned.
  1664. for pid in _scan_bambu_ffmpeg_pids():
  1665. if pid in active_pids:
  1666. continue
  1667. logger.info("Killing orphaned ffmpeg process found via /proc (pid=%d)", pid)
  1668. try:
  1669. os.kill(pid, signal.SIGKILL)
  1670. except (ProcessLookupError, OSError):
  1671. pass
  1672. _spawned_ffmpeg_pids.pop(pid, None)
  1673. cleaned += 1
  1674. # 2. Clean up _spawned_ffmpeg_pids entries for dead processes
  1675. for pid in list(_spawned_ffmpeg_pids):
  1676. try:
  1677. os.kill(pid, 0) # existence check
  1678. except (ProcessLookupError, OSError):
  1679. _spawned_ffmpeg_pids.pop(pid, None)
  1680. # 3. Clean up _active_streams entries with dead processes
  1681. dead_streams = [sid for sid, proc in _active_streams.items() if proc.returncode is not None]
  1682. for sid in dead_streams:
  1683. proc = _active_streams.pop(sid, None)
  1684. if proc:
  1685. _spawned_ffmpeg_pids.pop(proc.pid, None)
  1686. cleaned += 1
  1687. # 4. Kill stale active streams (alive but no frames for >30s)
  1688. # Uses per-stream timestamps to avoid false "fresh" readings from newer streams
  1689. for sid, proc in list(_active_streams.items()):
  1690. if proc.returncode is not None:
  1691. continue
  1692. # Per-stream frame time is authoritative; fall back to per-printer
  1693. stream_last_frame = _stream_last_frame_times.get(sid)
  1694. if stream_last_frame is None:
  1695. try:
  1696. printer_id = int(sid.split("-", 1)[0])
  1697. except (ValueError, IndexError):
  1698. continue
  1699. stream_last_frame = _last_frame_times.get(printer_id)
  1700. spawn_time = _spawned_ffmpeg_pids.get(proc.pid, now)
  1701. if stream_last_frame is None:
  1702. stream_last_frame = spawn_time
  1703. if now - spawn_time > 60 and now - stream_last_frame > 30:
  1704. logger.info("Killing stale ffmpeg stream %s (no frames for %.0fs)", sid, now - stream_last_frame)
  1705. # Signal the generator to stop reconnecting
  1706. event = _disconnect_events.get(sid)
  1707. if event:
  1708. event.set()
  1709. try:
  1710. proc.kill()
  1711. # Bounded (#2580): an unreaped SIGKILLed ffmpeg must not hang
  1712. # the periodic cleanup loop — this janitor is the safety net
  1713. # that recovers stalled streams, so it can least afford to
  1714. # block. The /proc scan above retries the kill next pass.
  1715. await asyncio.wait_for(proc.wait(), timeout=_FFMPEG_KILL_TIMEOUT)
  1716. except (ProcessLookupError, OSError):
  1717. pass
  1718. except TimeoutError:
  1719. logger.error(
  1720. "ffmpeg (pid=%d) did not exit within %.1fs of SIGKILL; abandoning wait (stream_id=%s)",
  1721. proc.pid,
  1722. _FFMPEG_KILL_TIMEOUT,
  1723. sid,
  1724. )
  1725. _active_streams.pop(sid, None)
  1726. _disconnect_events.pop(sid, None)
  1727. _stream_last_frame_times.pop(sid, None)
  1728. _spawned_ffmpeg_pids.pop(proc.pid, None)
  1729. cleaned += 1
  1730. # 4. Clean stale chamber stream entries
  1731. dead_chamber = [sid for sid, (_reader, writer) in _active_chamber_streams.items() if writer.is_closing()]
  1732. for sid in dead_chamber:
  1733. _active_chamber_streams.pop(sid, None)
  1734. cleaned += 1
  1735. if cleaned:
  1736. logger.info("Cleaned up %d orphaned camera stream(s)", cleaned)