camera.py 86 KB

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